简体   繁体   中英

How to keep Text print only once when asking a user to re-enter some string in loop in Java

I want to ask user to enter a number in type String, then check if it is number and if it's not then ask again to re-enter the string. I have a code like this:

    System.out.print("Enter first number: ");
    firstNum = scan.next();

    while(validateNum(firstNum) == false) {
        System.out.print("Please, enter number only: ");
        firstNum = scan.next();
    }

here's the validateNum method :

    private static boolean validateNum(String num) {
        if (num.matches("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")){
            return true;
        }
        return false;
    }

But the problem is that when I test it and enter some text with spaces it prints "Please, enter a number only" as many times as many spaces are in entered string. I tried to remove spaces from string and then check it but it still gives many prints.

You are using scan.next() . This returns what comes before a space. You want scan.nextLine() to scan the entire line the user inputs

Here is the docs on the Scanner class and it's methods.

In short:

next() : Scans for the next complete token

nextLine() : Scans the complete line

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