-8

My program requires user to enter a 4-digit number(int type). Currently, when the user enters any character other than numeric, the program crashes. My hope is that when the user enters a non-numeric character, the program can tell the user "Wrong input" then let the user re-enter.

Does exception handling work for this? Or is there any other good way to solve this?

Basilevs
  • 22,440
  • 15
  • 57
  • 102
Gavin
  • 97
  • 8

1 Answers1

0

If you are using scanner, you can use the nextInt() method with the condition hasNextInt() which would only read integer inputs. Have a look at this post for example:

Taken from the above mentioned post.

Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
    while (!sc.hasNextInt()) sc.next();
    num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);

Also you can look at the documentation for scanner's nextInt() here

Community
  • 1
  • 1
anirudh
  • 4,116
  • 2
  • 20
  • 35