Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent user from entering whitespace in Java

Tags:

java

I want the user to only enter his age. So I did this program :

Scanner keyb = new Scanner(System.in);  
int age;

while(!keyb.hasNextInt())
{
    keyb.next();
    System.out.println("How old are you ?");
}

age = keyb.nextInt();
System.out.println("you are" + age + "years old");

I found how to prevent user from using string by using the while loop with keyb.hasNextInt(), but how to prevent him from using the whitespace or from entering more input than his age ?

For example I want to prevent this kind of typing "12 m" or "12 12"

Also, how can I clear all existing data in the buffer ? I'm facing an infinite loop when I try to use this :

while(keyb.hasNext())
  keyb.next();
like image 384
Spn Avatar asked Dec 24 '22 05:12

Spn


1 Answers

You want to get the whole line. Use nextLine and check that for digits e.g.

String possibleAge = "";
do {
    System.out.println("How old are you ?");
    possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))
like image 87
Murat Karagöz Avatar answered Jan 15 '23 12:01

Murat Karagöz