While loop with Scanner

时间:2017-08-04 13:05:18

标签: java while-loop try-catch

why isn't this code working as expected?

public class FinalTest {
  public static void main (String [] args) {

    Scanner in = new Scanner(System.in);
    int k = 0;

    boolean askForInput = true;

    while ( askForInput ) {
      System.out.print("Enter an integer: ");
      try {
        k = in.nextInt();
        askForInput = false;
      } catch (InputMismatchException e) {
        System.out.println("ERR: Not an integer!!");
      }
    }

  }
}

nextInt() tries to scan the input as an int, and if it is not an int, it should throw an exception ERR: Not an integer. What bugs me is, why doesn't it prompt for input again? It just keeps printing the ERR message on screen.

4 个答案:

答案 0 :(得分:2)

The nextInt() call does not consume your input (e.g. "abc") if it isn't an integer. So the next time in the loop it still sees the "abc" that you already entered, and that goes on forever. So better use Integer.parseInt(in.next()):

public static void main (String [] args) {

    Scanner in = new Scanner(System.in);
    int k = 0;

    boolean askForInput = true;

    while ( askForInput ) {
        System.out.print("Enter an integer: ");
        try {
            k = Integer.parseInt(in.next());
            askForInput = false;
        } catch (NumberFormatException e) {
            System.out.println("ERR: Not an integer!!");
        }
    }
}

答案 1 :(得分:0)

this is the correct form , you should start again the loop :

A you can see i put System.out.print("Enter an integer: "); inside catch to make it not reduntant.

 public static void main(String[] args){
            System.out.print("Enter an integer: ");
            Scanner in = null;
            int k = 0;

            boolean askForInput = true;

            while ( askForInput ) {

              in = new Scanner(System.in);
              try {
                k = in.nextInt();
                askForInput = false;
              } catch (InputMismatchException e) {
                System.out.println("ERR: Not an integer!!");
                askForInput = true;
                System.out.print("Enter an integer: ");

              }
            }
            System.out.print("End");

          }
        }

Output :

enter image description here

答案 2 :(得分:0)

From the documentation of nextInt:

This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

In other words, nextInt leaves the token in the token stream if it is not recognized as a number. One fix might be to use next() to discard the token in the catch block.

答案 3 :(得分:0)

When you execute the try block, askForInput is getting changed to false regardless of the value of k ending your loop on the first iteration every time. Try this instead:

 while ( askForInput ) {
      System.out.print("Enter an integer: ");
      try {
        k = in.nextInt();
        askForInput = false;
      } catch (InputMismatchException e) {
        System.out.println("ERR: Not an integer!!");
        askForInput = true; //add this line resetting askForInput to true
      }
    }