You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多数值Java计算器开发:求四则运算逻辑及数组存储方案

Java计算器完善乘除运算的实现方案

核心思路

基于现有加减运算框架,扩展乘除分支逻辑;通过遍历numbers和ops数组逐次执行运算,将每一步结果存入ans数组,并按指定格式输出。若需遵循数学运算优先级(乘除优先于加减),则改用栈结构实现优先级调度。

分步实现

1. 输入合法性校验

运算前先做基础校验,避免数组越界或非法运算符:

  • 确保numbers数组长度 = ops数组长度 + 1(每两个数值对应一个运算符)
  • 校验ops数组中的元素仅为+、-、*、/
  • 除法运算时额外判断除数是否为0

2. 基础版(顺序运算)

适用于无需优先级的场景,直接按数组顺序依次执行运算:

public class BasicCalculator {
    public static void main(String[] args) {
        // 示例输入
        int[] numbers = {10, 5, 2, 3};
        char[] ops = {'/', '*', '+'};
        int[] ans = new int[ops.length]; // 存储每一步运算结果

        // 初始值为第一个数值
        int currentResult = numbers[0];

        for (int i = 0; i < ops.length; i++) {
            int nextNum = numbers[i + 1];
            char op = ops[i];

            // 扩展乘除运算逻辑
            switch (op) {
                case '+':
                    currentResult += nextNum;
                    break;
                case '-':
                    currentResult -= nextNum;
                    break;
                case '*':
                    currentResult *= nextNum;
                    break;
                case '/':
                    if (nextNum == 0) {
                        throw new ArithmeticException("除数不能为0");
                    }
                    currentResult /= nextNum;
                    break;
                default:
                    throw new IllegalArgumentException("不支持的运算符: " + op);
            }

            // 存入结果数组
            ans[i] = currentResult;
            // 按格式输出单步运算
            System.out.printf("%d%c%d=%d%n", numbers[i], op, nextNum, ans[i]);
        }
    }
}

3. 优化版(支持运算优先级)

若需遵循数学优先级(乘除先于加减),使用栈结构实现调度:

import java.util.Stack;

public class PriorityCalculator {
    public static void main(String[] args) {
        double[] numbers = {10, 5, 2, 3};
        char[] ops = {'/', '*', '+'};
        double[] ans = new double[ops.length];
        int ansIndex = 0;

        Stack<Double> numStack = new Stack<>();
        Stack<Character> opStack = new Stack<>();
        numStack.push(numbers[0]);

        for (int i = 0; i < ops.length; i++) {
            char currentOp = ops[i];
            double nextNum = numbers[i + 1];

            // 先处理栈中优先级更高或相等的运算符
            while (!opStack.isEmpty() && isHigherOrEqualPriority(opStack.peek(), currentOp)) {
                double b = numStack.pop();
                double a = numStack.pop();
                char op = opStack.pop();
                double res = compute(a, b, op);
                numStack.push(res);
                ans[ansIndex++] = res;
                System.out.printf("%.2f%c%.2f=%.2f%n", a, op, b, res);
            }

            opStack.push(currentOp);
            numStack.push(nextNum);
        }

        // 处理剩余的运算符
        while (!opStack.isEmpty()) {
            double b = numStack.pop();
            double a = numStack.pop();
            char op = opStack.pop();
            double res = compute(a, b, op);
            numStack.push(res);
            ans[ansIndex++] = res;
            System.out.printf("%.2f%c%.2f=%.2f%n", a, op, b, res);
        }

        System.out.println("最终结果: " + numStack.pop());
    }

    // 判断运算符优先级:乘除 > 加减
    private static boolean isHigherOrEqualPriority(char op1, char op2) {
        return (op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-');
    }

    // 执行运算
    private static double compute(double a, double b, char op) {
        switch (op) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            case '/':
                if (b == 0) throw new ArithmeticException("除数不能为0");
                return a / b;
            default: throw new IllegalArgumentException("不支持的运算符: " + op);
        }
    }
}

关键注意事项

  • 除数为0处理:必须在除法分支中加入判断,否则会抛出运行时异常导致程序崩溃
  • 数值类型选择:若需支持小数或高精度计算,用double或BigDecimal替代int,避免整数除法的精度丢失问题
  • 输入校验:在运算前添加数组长度匹配、运算符合法性的校验逻辑,提升程序健壮性

内容的提问来源于stack exchange,提问作者Programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:03:37