所以我试图让用户输入他们的答案作为布尔值,然后进行错误检查,但这似乎不起作用。 我是否走在正确的轨道上,或者有更好的方法来做到这一点? 我曾考虑过在输入是字符串的情况下执行此操作,然后仅将其与我分配给"true"和"false"的其他两个字符串进行检查,但是我的while循环:
while (!continueGame.equalsIgnoreCase(answerTrue) && !continueGame.equalsIgnoreCase(answerFalse)) {
System.out.println("Would you like to try again? (true/false)");
continueGame = keyboard.nextBoolean();
System.out.println();
}
也没用。 我相当确定这与我的不是有关,但我不确定为什么。 无论如何,以下是我使用布尔值而不是字符串进行错误检查的方法。 字符串版本基本上相同,但只是针对字符串进行了修改。
public static boolean continueGame() {
boolean continueGame;
System.out.println("Would you like to try again? (true/false)n");
continueGame = keyboard.nextBoolean();
System.out.println();
while (continueGame != true && continueGame != false) {
System.out.println("Would you like to try again? (true/false)");
continueGame = keyboard.nextBoolean();
System.out.println();
}
if (continueGame) {
return true;
}
else {
System.out.println("We accept your surrender.");
return false;
}
} //End continueGame method
基本上,
我将交换循环的工作方式,以便可以达到中断条件。
import java.*;
import java.util.Scanner;
public class Loop
{
public static void main(String[] args)
{
boolean continueGame=true;
Scanner keyboard = new Scanner(System.in);
System.out.println("Would you like to try again? (true/false)n");
continueGame = keyboard.nextBoolean();
while (continueGame) {
System.out.println("Would you like to try again? (true/false)");
continueGame = keyboard.nextBoolean();
if(!continueGame)
{
System.out.println("We accept your surrender.");
}
}
}
}
while(true) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Would you like to try again? (true/false)");
if(keyboard.hasNextBoolean()){
continueGame = keyboard.nextBoolean();
System.out.println();
break;
}
}
这将无限期地提示用户输入 true/false,直到他们输入有效的布尔值。然后它将脱离循环,您可以继续执行其余代码。