0

所以我试图让用户将他们的答案作为布尔值输入,然后进行错误检查,但这似乎不起作用。我在正确的轨道上还是有更好的方法来做到这一点?我曾考虑过在输入是字符串的情况下执行此操作,然后将其与分配给“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
4

2 回答 2

0

基本上我只是交换你的循环的工作方式,所以可以达到破坏条件。

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.");
    }
   }
 }
}
于 2015-01-30T22:04:15.047 回答
-1
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;
    }

}

这将无限期地提示用户输入真/假,直到他们输入有效的布尔值。然后它将跳出循环,您可以继续执行其余代码。

于 2015-01-30T22:47:25.547 回答