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

Flow
  • 169
  • 2
  • 2
  • 10

2 Answers2

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);
ATG
  • 1,679
  • 14
  • 25
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.

Aaron
  • 652
  • 4
  • 10