While loop that is not working with Try/Catch statements

前端 未结 3 1075
太阳男子
太阳男子 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: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()

提交回复
热议问题