简体   繁体   中英

How to check for empty inputs in java scanner

After some digging, I have not been able to find a satisfactory way to achieve a condition in a do-while loop, so that the scanner will ignore empty inputs.

Attempted code:

String name = "";
boolean flag_name= false;
do{
    System.out.print("Name: ");
    if(scanner.hasNextInt()){
        int number = scanner.nextInt();
        scanner.nextLine();
        System.out.printf("\"%s\" is not a valid name...\n", number);
    }else{
        name = scanner.nextLine();
        if(!name.equals("")){
            if(name.length() <= 2){
                System.out.println("The name is too short (min: 3)...");
            }else if(name.length >= 20){
                System.out.println("The name is too long (max: 20)...");
            }else{
                flag_name = true;
            }
        }
    }
}while(!flag_name);

expected output:

Name: 
Name:
Name:
Name:
Name:
Name: willy
Age: 

actual output:

Name: 




willy
Name: Name: Name: Name: Name: Age: 

I should have specified that I wanted to provide custom error messages, not just validation.

Thanks to @Popeye I figured out that hasNextXXX methods are not so helpful when you need multiple validations. Instead I saved my input and validate from there.

  1. Implemented a while loop that will check wether the input is empty or not on each submit.

  2. Improved the numeric validation, not just for ints, but for any kind of number via regex.

  3. Thanks to @BasilBourque improved .isEmpty() instead of .equals("") .

public static boolean isNumeric(String str){
    return str.matches("-?\\d+(\\.\\d+)?");
}

String name = "";
boolean isValidName = false;
do{
    System.out.print("Name: ");
    name = scanner.nextLine();
    while(!name.isEmpty() && !isValidName){
        if(Utils.isNumeric(name)){
            System.out.printf(" \"%s\" Is not a valid name.\n\n", name);
            break;
        }else{
            if(name.length() < 3){
                System.out.printf(" \"%s\" Name is too short... (min 3)\n\n", name);
                break;
            }else if(name.length() > 20){
                System.out.printf(" \"%s\"Name is too long... (max 20)\n\n", name);
                break;
            }else{
                isValidName = true;
            }
        }
    }
}while(!isValidName);

I improved my solution with the following code:

// Regex validation of number
public static boolean isNumeric(String str){
    return str.matches("-?\\d+(\\.\\d+)?");
}

// Validation of the string input with custom error messages.
public static boolean isValidName(String name){
    if(Utils.isNumeric(name)){
        System.out.printf("\"%s\" Is not a valid name.\n\n", name);
    }else{
        if(name.length() < 3){
            System.out.printf("\"%s\" Too short... (min 3)\n\n", name);
        }else if(name.length() > 20){
            System.out.printf("\"%s\" Too long... (max 20)\n\n", name);
        }else{
            return true;
        }
    }
    return false;
}

// Ask for input code block
String name;
do{
    System.out.print("Name: ");
    name = scanner.nextLine();
    if(!name.isEmpty()){
        if(Utils.isValidName(name)){
            break;
        }
    }
}while(true);
  1. Saved my input in a variable and validate from there.
  2. Implemented a regex mehod for checking not only integers but any kind of number.
  3. Separated the validation of the actual input with custom error messages on another method.
  4. Implemented a name.isEmpty() instead of name.equals("") for discarding empty inputs (enter key presses).

The original question was about on how to ignore emtpy inputs in the loop but thanks to your comments I improved my entire algorithm.

Thank you.

I would say your logic is flawed. Instead of looping through like this, consider to break down your method into multiple function.

Let me write an algorithm

static boolean isValidName(String input) {
    /*
     * enter code here
    */
    return true for valid
}
    public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    String name = "";
    do {
        System.out.print("Name: ");
        if (isValidName(name)) {
            break;
        }
    } while ((name = scanner.nextLine()) != null);
    System.out.println(name);
}

hasNextInt is not the best way to check if user has inputted number or not. You have to consider validation more thoroughly.

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