我想阻止用户提供空输入,这是我的代码
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接受来自用户的空输入?
答案 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: ");
}