简体   繁体   中英

Prevent user from entering whitespace in 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();

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

String possibleAge = "";
do {
    System.out.println("How old are you ?");
    possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))

Your problem is that the default behaviour of Scanner is to use any whitespace as the delimiter. This includes spaces. This means that a 3 a is in fact three tokens, not one. You can change the delimiter to a new line so that a 3 a becomes a single token, which will then return false for hasNextInt .

I've also added an initial question, because in your example the first input was taken before asking any questions.

Scanner keyb = new Scanner(System.in);
keyb.useDelimiter("\n"); // You can try System.lineSeparator() but it didn't work in IDEA
int age;

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

age = keyb.nextInt();
System.out.println("You are " + age + " years old");
String age = "11";
        if (age.matches(".*[^0-9].*")) {
            System.out.println("Invalid age");
        } else {
            System.out.println("valid age");
        }

If age contains other then digits then it will print invalid age.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM