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

Java Scanner循环二次调用时跳过输入问题及解决

基于OOP的计算器类Scanner输入跳过问题解决

问题现象

基于OOP思想开发Calculator计算器类时,循环中第二次调用userInputOp()方法时,Scanner会跳过输入步骤,直接执行后续逻辑,导致无法正常获取运算符输入。

问题代码

Calculator() {
    System.out.println("Calculator Created");
    while(!ifExit){
        showInstructions();
        userInputOp();
        ifExit();
        if(this.ifExit) {
            break;
        }
        userInputNum();
        compute(this.n1,this.n2);
        printResults();
        this.op = null;
    }
}
private void userInputOp() {
    System.out.println("userInputOp");
    System.out.print("Enter operator symbol: ");
    this.op = sc.nextLine();
}
private void ifExit() {
    System.out.println("ifExit");
    if(this.op.equals("0"))
        this.ifExit = true;
}

异常输出

**Below is the 2nd output of the loop**
====================================
      | BASIC CALCULATOR |      
      ADDITION -       ( + )
      SUBTRACTION -    ( - )
      MULTIPLICATION - ( x )
      DIVISION -       ( / )
      MODULO -         ( % )
      EXIT -           ( 0 )
====================================
userInputOp
Enter operator symbol: ifExit
Enter first number: 

原因分析

Scanner的nextDouble()方法仅读取输入的数字内容,不会处理数字输入完成后用户按下的换行符。当循环进入第二次迭代时,userInputOp()中的sc.nextLine()会直接读取这个残留的换行符,误以为用户完成了输入,从而跳过实际的运算符输入步骤。

解决方案

在使用nextDouble()获取数字后,添加sc.nextLine()清除输入缓冲区中残留的换行符,修改后的userInputNum()方法代码如下:

private void userInputNum() {
    System.out.print("Enter first number: ");
    this.n1 = sc.nextDouble();
    sc.nextLine(); // 清除残留换行符
    System.out.print("Enter second number: ");
    this.n2 = sc.nextDouble();
    sc.nextLine(); // 清除残留换行符
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:05:28