在Java readLine中防止空输入

时间:2014-01-20 09:03:25

标签: java readline

我想阻止用户提供空输入,这是我的代码

private void guessWord(){
    String input = readLine("Your guess: ");
    while(!isValidInput(input)){
        println("Your input is invalid, please try again.");
        input = readLine("Your guess: ");
    }
    char letter = input.charAt(0);
    letter = Character.toUpperCase(letter);
    if(!(subtituteLetter(letter))){
        println("There are no " + letter + "\'s in the word.");
        life -=1 ;
    }

}

我不想将空输入传递给我的 isValidInput ,那么如何阻止readLine接受来自用户的空输入?

2 个答案:

答案 0 :(得分:1)

您可以简单地强制用户在循环中输入非空字符串。

private void guessWord(){
    String input;
    do{
    input = readLine("Your guess: ");
    }
    while(input.isEmpty());

    while(!isValidInput(input)){
        println("Your input is invalid, please try again.");
        input = readLine("Your guess: ");
    }
    char letter = input.charAt(0);
    letter = Character.toUpperCase(letter);
    if(!(subtituteLetter(letter))){
        println("There are no " + letter + "\'s in the word.");
        life -=1 ;
    }
}

答案 1 :(得分:1)

用这个循环替换你:

    while(input.isEmpty() || !isValidInput(input)){
        println("Your input is invalid, please try again.");
        input = readLine("Your guess: ");
    }