简体   繁体   English

循环重新启动时,为什么我的第一个打印语句打印两次?

[英]Why does my first print statement print twice when the loop restarts?

Why does "Enter an operation (+, -, *, /, quit)" print twice when I enter an invalid input for the first or second numeric value? 当我输入第一个或第二个数字值的无效输入时"Enter an operation (+, -, *, /, quit)"为什么"Enter an operation (+, -, *, /, quit)"打印两次? The loop is supposed to restart and print "Enter an operation (+, -, *, /, quit)" once after an invalid input. "Enter an operation (+, -, *, /, quit)"无效后"Enter an operation (+, -, *, /, quit)"循环应重新启动并打印"Enter an operation (+, -, *, /, quit)"

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    int i = 1;
    while(i > 0){
        String operation = "";
        int firstInt = 0;
        int secondInt = 0;
        double firstDouble = 0.0;
        double secondDouble = 0.0;
        int intAnswer = 0;
        double answer = 0.0;
        boolean first = false;
        boolean second = false;

        System.out.println("Enter an operation (+, -, *, /, quit)");
        operation = scnr.next();
        if(operation.equals("+")|| operation.equals("-") || operation.equals("*") || operation.equals("/")){
            System.out.println("Enter first numeric value");
            if(scnr.hasNextInt()){
                firstInt = scnr.nextInt();
                first = true;
            }else if(scnr.hasNextDouble()){
                firstDouble = scnr.nextDouble();
            }
            else{
                continue;
            }
            System.out.println("Enter second numeric value");
            if(scnr.hasNextInt()){
                secondInt = scnr.nextInt();
                second = true;
            }else if(scnr.hasNextDouble()){
                secondDouble = scnr.nextDouble();
            }
            else{
                continue;
            }
        }
        else if(operation.equals("quit")){
            System.exit(0);
            scnr.close();
            break;
        }

    }

}

Using Scanner.nextInt() and so on leaves the scanner buffer open, since it does not consume the whole line, but only nearest primitive value and the rest of the line is stored in the scanner buffer and is only consumed by new line call. 使用Scanner.nextInt()等会使扫描器缓冲区保持打开状态,因为它不会占用整行,而是仅将最接近的原始值和该行的其余部分存储在扫描器缓冲区中,并且仅由新的行调用使用。 This leads to lot of unexpected and hard to troubleshoot bugs. 这会导致很多意外情况,并且难以解决错误。

Better practice when using scanner to get primitive data types is to use 使用扫描仪获取原始数据类型时的更好做法是使用

double yourDouble = Double.parseDouble(Scanner.nextLine());
//for int you use Integer.parserInt(Scanner.nextLine()

This way the scanner consumes whole line and nothing is stored in the buffer and you don't get the headache from misbehaving output/input streams. 这样一来,扫描程序就消耗了整行,并且缓冲区中没有存储任何内容,而且您不会因输出/输入流出现异常而感到头疼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM