0

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.

py9
  • 598
  • 5
  • 15

4 Answers4

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!!");
        }
    }
}
Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
  • that makes sense. But why isn't it printing "Enter an integer" as well? Since that is the beginning of the loop – py9 Aug 04 '17 at 13:19
  • @py9 It prints it for me. Double-check your code (if it is saved before compilation/execution) and make sure you are using solution posted here. – Pshemo Aug 04 '17 at 13:22
  • my bad. Works fine. Thanks! – py9 Aug 04 '17 at 13:29
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

Frank
  • 873
  • 1
  • 7
  • 17
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.

Community
  • 1
  • 1
Botje
  • 26,269
  • 3
  • 31
  • 41
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
      }
    }
ja08prat
  • 154
  • 10