0

I'm trying to validate for an input of either 1 or 2. But, with this code, if you enter letters, it crashes the program.

How can this be fixed?

System.out.print("Choice: ");
userSelection  = keyboard.nextInt();

while (flag == 0)
{
    if (userSelection == 1 || userSelection == 2)
    {
        flag = 1;
    }
    if(Character.isDigit(userSelection))
    {
        flag = 1;
    }
    else 
    {
        flag = 0;
    }
    if (flag == 0)
    {
        //this is a system clear screen to clear the console
        System.out.print("\033[H\033[2J");  
        System.out.flush(); 

        //display a warning messege that the input was invalid
        System.out.println("Invalid Input! Try again, and please type in selection 1 or selection 2 then hit enter");
        System.out.print("Choice: ");
        userSelection  = keyboard.nextInt();
    }
}
Pang
  • 8,605
  • 144
  • 77
  • 113
Spike655
  • 1
  • 4
  • Use try and catch that way it doesn't break the program. You should look at the documentation it is really useful especially in java, you try/catch everything :D – Denis Radinski Feb 12 '16 at 02:05

2 Answers2

1

nextInt expects the user to type an integer. It will fail otherwise.

You may want to construct something with nextLine (which reads a line of input that you can then inspect, reading single characters as they are being typed is tricky in Java).

Community
  • 1
  • 1
Thilo
  • 241,635
  • 91
  • 474
  • 626
0

Try this code snippet:

try (Scanner scanner = new Scanner(System.in)) {
   int choice;
   while (true) {
       System.out.print("Choice: ");
       if (!scanner.hasNextInt()) {
            scanner.nextLine();//read new line character
            System.err.println("Not a number !");
            continue; // read again
       }
       choice = scanner.nextInt(); //got numeric value
       if (1 != choice && 2 != choice) {
             System.err.println("Invalid choice! Type 1 or 2 and press ENTER key.");
             continue; //read again
       }
       break;//got desired value
   }
   System.out.printf("User Choice: %d%n", choice);
}