java - 我不明白为什么扫描在这段代码上不起作用

标签 java string java.util.scanner calculator

我刚刚开始编写代码是为了好玩,并尝试制作一个基本的计算器, 但我遇到了一个问题。

底部有我的代码

<小时/>
import java.util.Scanner;

public class practice {

public static void main(String[] args) {
    double temp1, temp2;
    int temp4 = 1;
    int end = 0;
    **String temp3,temp5;**
    calculator cal = new calculator();
    Scanner scan = new Scanner(System.in);


    while(end==0){
    System.out.println("Please put your first number to calculate");
    temp1 = scan.nextDouble();
    System.out.println("Please put your second number to calculate");
    temp2 = scan.nextDouble();

    System.out.println("What arithmetic operation you want to do?(+,-,/,*)");

    **temp3 = scan.nextLine();**

    if(temp3.equals("+")){
        System.out.println("Result is" + cal.add(temp1, temp2));
    }

    else if(temp3.equals("-")){
        System.out.println("Result is" + cal.subtract(temp1, temp2));
    }

    else if(temp3.equals("*")){
        System.out.println("Result is" + cal.multiply(temp1, temp2));
    }

    else if(temp3.equals("/")){
        System.out.println("Result is" + cal.divide(temp1, temp2));
    }
    else
        System.out.println("You got wrong operator");

    while(temp4==1){
        System.out.println("Now you want to quit(press y/n)");
        temp5 = scan.nextLine();

        if(temp5.equals("y")){
            temp4=0;
            end=1;
        }

        else if(temp5.equals("n")){
            System.out.println("Then here we go again");
            temp4=0;
        }

        else
            System.out.println("You put wrong words");
        }
    }
}
}
<小时/>

我不明白为什么 temp3 不起作用。

我想检查我是否犯了错误,所以我制作了 temp5 但它有效。

谁能解释一下为什么吗?

最佳答案

问题是 nextDouble() 没有用完输入第二个 double 时使用的换行符。因此 nextLine() 看到换行符已经存在并使用它。

添加额外的 nextLine() 调用以使用第二个数字中的换行符。

temp2 = scan.nextDouble();

// Add consuming of new line here.
String dummy = scan.nextLine();

System.out.println("What arithmetic operation you want to do?(+,-,/,*)");

temp3 = scan.nextLine();

关于java - 我不明白为什么扫描在这段代码上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18647948/

相关文章:

java - 在 Java 中混合音频文件

java - 如何计算算术表达式(字符串)并返回结果?

java.util.NoSuchElementException - 扫描仪读取用户输入

arrays - 在uilabel多行swift中拆分字符串

Python - 定义全局字符串变量

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - Java中如何让每次按回车键时弹出一个新文本?

Java 事件处理程序命名约定

java - 部署 Thrift Java 服务实现的最佳方式是什么?

java - java中的同步和代码重新排序