Java: Infinite loop using Scanner in.hasNextInt()

前端 未结 4 1527
Happy的楠姐
Happy的楠姐 2020-11-27 19:30

I am using the following code:

while (invalidInput)
{
    // ask the user to specify a number to update the times by
    System.out.print(\"Specify an intege         


        
4条回答
  •  爱一瞬间的悲伤
    2020-11-27 19:56

    Flag variables are too error prone to use. Use explicit loop control with comments instead. Also, hasNextInt() does not block. It's the non-blocking check to see if a future next call could get input without blocking. If you want to block, use the nextInt() method.

    // Scanner that will read the integer
    final Scanner in = new Scanner(System.in);
    int inputInt;
    do {  // Loop until we have correct input
        System.out.print("Specify an integer between 0 and 5: ");
        try {
            inputInt = in.nextInt(); // Blocks for user input
            if (inputInt >= 0 && inputInt <= 5)  { 
                break;    // Got valid input, stop looping
            } else {
                System.out.println("You have not entered a number between 0 and 5. Try again.");
                continue; // restart loop, wrong number
             }
        } catch (final InputMismatchException e) {
            System.out.println("You have entered an invalid input. Try again.");
            in.next();    // discard non-int input
            continue;     // restart loop, didn't get an integer input
        }
    } while (true);
    

提交回复
热议问题