0
int i;
Scanner scan = new Scanner(System.in) {
i = scan.nextInt();
}

What I want to do is to catch the error in scanner when a user inputs a character instead of an integer. I tried the code below but ends up calling for another user input (bec. of calling another scan.nextInt() in assigning value to i after validating the first scan.nextInt() of numeric only):

int i;
Scanner scan = new Scanner(System.in) {

    while (scan.hasNextInt()){
    i = scan.nextInt();
    } else {
    System.out.println("Invalid input!");
    }
}
0

1 Answer 1

1

Your logic seems a bit off, you have to consume an input if it isn't valid. Also, your anonymous block seems very odd. I think you wanted something like

int i = -1; // <-- give it a default value.
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) { // <-- check for any input.
    if (scan.hasNextInt()) { // <-- check if it is an int.
        i = scan.nextInt(); // <-- get the int.
        break; // <-- end the loop.
    } else {
        // Read the non int.
        System.out.println("Invalid input! " + scan.next()); 
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had an error using "while (scan.hasNext())" so I changed it to "if (scan.hasNext())" and my problem was solved! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.