2

I'm writing a very simple program and where I am getting 3 ints from a user and want to check to make sure they are all ints before storing them into seperate variables to process. The check I've used works on the first input but fails and throws the exception on the second two.

boolean properInt = scanner.hasNextInt();
    int largest = Integer.MAX_VALUE;
    boolean anError = false;


    while(properInt=false){
        anError=true;
        System.out.println("Invalid number...whole numeric values only");
    }

    while(properInt =true){

    int a= scanner.nextInt();
        System.out.println("you entered "+ a);
    int b = scanner.nextInt();
        System.out.println("you entered "+ b);
    int c= scanner.nextInt();
        System.out.println("you entered "+ c);

}

John Welch
  • 23
  • 2
  • `while(properInt=false)` doesn't do what you think it does (= is not the same as ==). Same for `while(properInt =true)` – Pshemo Jan 13 '19 at 23:58
  • I fixed it to if(properInt== false).....The while loop caused an endless loop...but the same issue I talked about happens....it catches the first itteration but not the second or third. – John Welch Jan 14 '19 at 00:08

1 Answers1

0

Reason is when you use any of the nextXxx(...), the scanner cursor is reset to where it was before the call. When you press 'enter' key after entering a valid number, scanner ignores the 'character' (enter). However, when you enter an invalid value, an exception is thrown and the enter key character is seen by the next 'nextInt' as another condition and so won't work.

I would suggest using nextLine and then Integer.ParseInt and catching NumberFormatException.

Also, your while loop check is incorrect.

properInt=false is a statement.

while(properInt==false) is a condition..

English is not my strength so if its confusing let me know.

Gauravsa
  • 5,551
  • 1
  • 13
  • 23