简体   繁体   中英

Scanner input being skipped inside while loop

first post so go easy on me. I know this is a simple oversight on my part but I'm having trouble visualizing what is actually happening here so any insight would be much appreciated.

The issue is my current code is repeatedly printing "Invalid number format. Try again." into the console upon entering an incorrect operand ie "2a + 2" I'm specifically asked to use nextDouble and next in this scenario.

Having tried to fix this on my own I'm led to believe its from calling nextDouble and next after each other, requiring the use of nextLine but I still don't understand why exactly.

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    boolean repeat = true;
    double n1,n2;
    String op;

    System.out.print("Enter a simple mathematical formula: ");

    while(repeat){
        try{

        n1 = in.nextDouble();
        op = in.next();
        n2 = in.nextDouble();

        switch(op){
            case "+":
                System.out.println("Result: " + (n1 + n2));
                break;
            case "-":
                System.out.println("Result: " + (n1 - n2));
                break;
            case "/":
                System.out.println("Result: " + (n1 / n2));
                break;
            case "*":
                System.out.println("Result: " + (n1 * n2));                     
                break;
            default:
                System.out.println("Invalid Operator. Try again.");
                continue;
            }

            repeat = false;

        }catch(InputMismatchException e){
            System.out.println("Invalid number format. Try again.");
        }
    }
    in.close();
}

The .next methods don't consume any input if a failure occurs. This means that the next time through the loop they will just read the same bad input and fail the same way.

To fix this, just call .nextLine() if an error occurs to skip the offending input line entirely.

From the documentation of Scanner.nextDouble() :

If the translation is successful, the scanner advances past the input that matched.

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