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

Java可选运算计算器运行自动输出Invalid input问题求助

问题原因

  1. Scanner的nextInt()方法只会读取输入的整数部分,不会消费整数后面跟着的换行符。你输入第二个数字按下回车后,残留的换行符会被后面的nextLine()直接读取到,相当于拿到了空字符串,所以直接走到default分支输出Invalid input。
  2. 现有代码还存在两个逻辑问题:add分支的计算逻辑误写为乘法,且缺少减法、除法对应的case分支。

修复后完整代码

import java.util.Scanner;  // Import the Scanner class

public class calculator {
    public static void main(String args[]){
        Scanner sc= new Scanner(System.in);
        //System.in is a standard input stream  
        System.out.print("Enter first number- ");  
        int a = sc.nextInt();  
        System.out.print("Enter second number- ");  
        int b = sc.nextInt();  
        // 消费nextInt()残留的换行符
        sc.nextLine();
        System.out.print("Do you want to multiply, add, divide, or subtract? ");  
        String c = sc.nextLine();  
        switch(c) {
            case "multiply":
              System.out.print(a * b);
              break;
            case "add":
              // 修复加法计算逻辑
              System.out.print(a + b);
              break;
            case "subtract":
              System.out.print(a - b);
              break;
            case "divide":
              if (b == 0) {
                  System.out.print("除数不能为0");
              } else {
                  // 转double避免整数除法丢失小数
                  System.out.print((double)a / b);
              }
              break;
            default:
              System.out.print("Invalid input!");
        }
        sc.close();
    }
}

可选优化方案

你也可以把读取运算类型的代码替换为String c = sc.next();,next()方法会自动跳过开头的空白字符(包括残留的换行符),不需要额外加一行sc.nextLine()消费换行。当前场景下运算选项都是单个单词,该方案完全适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:54:01