简体   繁体   中英

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? The loop is supposed to restart and print "Enter an operation (+, -, *, /, quit)" once after an invalid input.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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