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

Java实现连续运算计算器无法存储上一次运算结果问题求助

Java连续运算计算器问题修复方案

原有代码核心问题

  • 未设置统一变量存储上一次运算结果,使用add/sub/mul/div四个独立变量分散存储,无法跨运算类型传递结果
  • 每次循环都会重新用初始输入的两个数字计算,会覆盖之前的运算结果
  • another变量初始值为0,首次运算如果是乘除逻辑会直接得到错误结果
  • 未适配运算符和继续选项的小写输入,比如用户输入小写y选择继续时会直接退出程序
  • 存在无实际作用的冗余代码another = another;

修正后完整代码

import java.util.Scanner;

public class Practice {
    public static void main(String[] args) {
        char choose, cont;
        Scanner u = new Scanner(System.in);

        // 首次输入两个初始数字
        System.out.print("输入第一个数字: ");
        double lastResult = Double.parseDouble(u.nextLine());
        System.out.print("输入第二个数字: ");
        double inputNum = Double.parseDouble(u.nextLine());

        do {
            System.out.print("\n选择运算类型\n[A]加法\n[B]减法\n[C]乘法\n[D]除法");
            System.out.print("\n\n请选择: ");
            choose = u.next().charAt(0);
            // 统一转大写,无需重复判断大小写
            choose = Character.toUpperCase(choose);

            switch (choose) {
                case 'A':
                    lastResult = lastResult + inputNum;
                    System.out.println("运算结果为 " + lastResult);
                    break;
                case 'B':
                    lastResult = lastResult - inputNum;
                    System.out.println("运算结果为 " + lastResult);
                    break;
                case 'C':
                    lastResult = lastResult * inputNum;
                    System.out.println("运算结果为 " + lastResult);
                    break;
                case 'D':
                    // 补充除零判断避免崩溃
                    if (inputNum == 0) {
                        System.out.println("错误:除数不能为0");
                        break;
                    }
                    lastResult = lastResult / inputNum;
                    System.out.println("运算结果为 " + lastResult);
                    break;
                default:
                    System.out.println("选择无效");
            }

            System.out.print("是否继续运算?[Y/N]: ");
            cont = u.next().charAt(0);
            cont = Character.toUpperCase(cont);
            if (cont == 'Y') {
                System.out.print("输入新的运算数字: ");
                inputNum = u.nextDouble();
            } else {
                System.out.println("程序结束");
            }
        } while (cont == 'Y');
        u.close();
    }
}

核心优化点说明

  • 新增lastResult变量统一存储每一次的运算结果,作为下一次运算的第一个操作数
  • 首次输入的两个数字分别赋值给lastResult和inputNum,后续运算直接复用这两个变量,无需重新读取初始值
  • 新增运算符、继续选项的大写转换逻辑,兼容用户大小写输入
  • 补充除零判断,避免非法运算导致程序异常
  • 移除无意义的冗余变量和代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 00:54:03