0

I'm trying to use while loop to ask the user to reenter if the input is not an integer

for eg. input being any float or string

      int input;

      Scanner scan = new Scanner (System.in);

      System.out.print ("Enter the number of miles: ");
      input = scan.nextInt();
      while (input == int)  // This is where the problem is
          {
          System.out.print("Invalid input. Please reenter: ");
          input = scan.nextInt();
          }

I can't think of a way to do this. I've just been introduced to java

1
  • Take a look at the Scanner.hasNext methods. There you can determine which type the next input is. Commented Sep 19, 2013 at 23:06

2 Answers 2

1

The issue here is that scan.nextInt() will actually throw an InputMismatchException if the input cannot be parsed as an int.

Consider this as an alternative:

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter the number of miles: ");

    int input;
    while (true) {
        try {
            input = scan.nextInt();
            break;
        }
        catch (InputMismatchException e) {
            System.out.print("Invalid input. Please reenter: ");
            scan.nextLine();
        }
    }

    System.out.println("you entered: " + input);
Sign up to request clarification or add additional context in comments.

Comments

1

The javadocs say that the method throws a InputMismatchException if the input doesn;t match the Integer regex. Perhaps this is what you need?

So...

int input = -1;
while(input < 0) {
  try {
     input = scan.nextInt();
  } catch(InputMismatchException e) {
    System.out.print("Invalid input. Please reenter: ");
  }
}

as an example.

2 Comments

Except -1 is probably a valid number as far as you're concerned. The answer below mine would work.
FYI: "below" quickly loses its meaning based on edits and a users setting as seen in the tab (i.e., oldest, ...).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.