计算器代码

  • Post author:
  • Post category:其他


import java.math.BigDecimal;

public class Calculator {


public static void main(String[] args) {


Calculator c = new Calculator();

    String[] nums  = {"1","9","2"};
    char[] chrs ={'+','X'};
    final String calculator = c.calculator(nums, chrs);
    System.out.println(calculator);
}

/**
 *  @:实现一个计算器,需要按照四则运算的法则来实现
 * 用户输入的是 操作数的数组, 和运算符数组
 *  1 + 2 X 3 对应的 就是 :  【1,2,3】 【‘+’,‘X’】
 *  2/7-3  对应的 就是 :  【2,7,3】   【‘/’,‘-’】
 */
public String calculator(String[] nums, char[] chrs) {
    if (nums.length == 0 || nums.length - chrs.length != 1) {
        return null;
    }
    if (nums.length == 1) {
        return nums[0];
    }
    for (int i = 0; i < chrs.length; i++) {
        if (chrs[i] == 'X' || chrs[i] == '/') {
            BigDecimal result;
            BigDecimal b1 = new BigDecimal(nums[i]);
            BigDecimal b2 = new BigDecimal(nums[i + 1]);
            if (chrs[i] == 'X') {
                result = b1.multiply(b2);
            } else {
                result = b1.divide(b2,4);
            }
            // 乘法 (除法)位置在第一个
            if (i == 0) {
                if (nums.length == 2) {
                    return result.toString();
                } else {
                    String[] newNum = new String[nums.length - 1];
                    newNum[0] = result.toString();
                    for (int j = 1; j < newNum.length; j++) {
                        newNum[j] = nums[j + 1];
                    }
                    return calculator(newNum, new String(chrs).substring(1).toCharArray());
                }
            } else {
                // 乘法 (除法)位置非第一个
                String[] newNum = new String[nums.length - 1];
                for (int j = 0; j < i; j++) {
                    newNum[j] = nums[j];
                }
                newNum[i] = result.toString();
                for (int j = i + 1; j < newNum.length; j++) {
                    newNum[j] = nums[j + 1];
                }
                final char[] chars = (new String(chrs).substring(0, i) + new String(chrs).substring(i + 1)).toCharArray();
                return calculator(newNum, chars);
            }
        }
    }
    BigDecimal result = new BigDecimal(nums[0]);
    for (int i = 0; i < chrs.length; i++) {
        if (chrs[i] == '+') {
            final BigDecimal bigDecimal = new BigDecimal(nums[i + 1]);
            result = result.add(bigDecimal);
        }
        if (chrs[i] == '-') {
            final BigDecimal bigDecimal = new BigDecimal(nums[i + 1]);
            result = result.subtract(bigDecimal);
        }
    }
    return result.toString();
}

}



版权声明:本文为qq_37931418原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。