While loop that is not working with Try/Catch statements

前端 未结 3 1074
太阳男子
太阳男子 2021-01-24 13:16

Im trying to give the user the opportunity to repeat an input after introducing something that has produced an error but something is not working because once the err i

相关标签:
3条回答
  • 2021-01-24 13:25

    You are not clearing/flushing the scanner buffer after each user input.

    • Use keyboard.nextLine() just before the end of while loop(after the catch block)

      OR

    • Declare the scanner object inside the while loop itself Scanner keyboard = new Scanner(System.in);

    See this

    Cheers!

    0 讨论(0)
  • 2021-01-24 13:27

    The problem is with the input.nextInt() command it only reads the int value. It would be even better, if you read the input through Scanner#nextLine and convert your input to integer using Integer#parseInt(String) method.

    This does work for me.

     public static void main(String[] args) {
        int err = 1;
        Scanner keyboard = new Scanner(System.in);
        while (err == 1) {
            err = 0;
            try {
                int dim = Integer.parseInt(keyboard.nextLine());
                System.out.println("done.. exit");
            } catch (Exception e) {
                System.out.println("Ups! What you entered is not an integer.");
                err = 1;
            }
        }
    }
    

    output

    dd
    Ups! What you entered is not an integer.
    23
    done.. exit
    

    next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

    nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

    for reading the entire line you can use nextLine()

    0 讨论(0)
  • 2021-01-24 13:40

    When you enter a non-integer the Scanner call to nextInt() doesn't consume the non-integer. You need to call keyboard.next() (or keyboard.nextLine()) to consume it. Something like,

    try {
        dim = keyboard.nextInt();
    } catch (Exception e) {
        System.out.printf("%s is not an integer.%n", keyboard.next());
        err = 1;
    }
    
    0 讨论(0)
提交回复
热议问题