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

Java实现计算器重复计算:do-while循环变量未找到报错解决

问题根因

编译报错来自Java的局部变量作用域限制:pressed变量声明在do代码块内部,而while的循环判断条件位于do块的作用域外,无法访问块内声明的局部变量,因此触发「找不到符号」的编译错误。

原代码还有两处影响运行稳定性的问题:

  • 每次循环都重新创建Scanner实例,属于不必要的资源开销
  • 除法分支未做除数为0的校验,输入0作为第二个数时会直接抛出算术异常崩溃
修复后可直接运行的代码
import java.util.Scanner;
public class Calculator {
    public static void main(String args[]) {
        // Scanner移到循环外初始化,全局复用
        Scanner typed = new Scanner(System.in);
        // 提前声明循环控制变量,保证while条件可正常访问
        int pressed;
        do{
            System.out.println("Please type: 1 for add, 2 for subtract, 3 for multiply or 4 for divide");
            int userInput = typed.nextInt();
            System.out.println("Please enter the first number to calculate:");
            double number1 = typed.nextDouble();
            System.out.println("Please enter the second number to calculate:");
            double number2 = typed.nextDouble();
            double result = 0;

            switch (userInput) {
                case 1:
                    result = number1 + number2;
                    break;
                case 2:
                    result = number1 - number2;
                    break;
                case 3:
                    result = number1 * number2;
                    break;
                case 4:
                    // 新增除零校验,避免运行时崩溃
                    if (number2 == 0) {
                        System.out.println("Error: cannot divide by zero");
                        System.out.println("Do you want to perform another calculation? Press 1 for yes or 2 for no.");
                        pressed = typed.nextInt();
                        continue;
                    }
                    result = number1 / number2;
                    break;
                default:
                    // 新增非法操作输入校验
                    System.out.println("Invalid operation selection, please input 1-4");
                    System.out.println("Do you want to perform another calculation? Press 1 for yes or 2 for no.");
                    pressed = typed.nextInt();
                    continue;
            }
            System.out.println("The answer is");
            System.out.println(result);
            System.out.println("Do you want to perform another calculation? Press 1 for yes or 2 for no.");
            pressed = typed.nextInt();

        }while(pressed == 1);
        // 用完关闭Scanner释放资源
        typed.close();
    }
}
关键修改说明
  • 将pressed变量的声明提到do-while循环外部,让while判断条件可以正常访问变量,直接解决编译报错
  • 把Scanner实例初始化移到循环外,循环内复用同一个对象,减少无意义的资源消耗
  • 将分散的多个if判断替换为switch分支,抽离公共的结果打印逻辑,减少重复代码
  • 新增除数为0、非法操作符输入的容错处理,避免程序异常崩溃
  • 循环结束后主动关闭Scanner实例,符合资源使用规范

修复后逻辑完全匹配需求:单次运算结束后展示询问提示,用户输入1则重新走完整计算流程,输入2则直接退出程序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:45:29