Java布尔输入错误检查

时间:2015-01-30 21:22:02

标签: java boolean user-input error-checking

所以我试图让用户输入他们的答案作为布尔值,然后进行错误检查,但这似乎并没有起作用。我是在正确的轨道上还是有更好的方法来做到这一点?我曾经考虑过在输入是一个字符串的地方做它,并且只是将它与我​​指定的其他两个字符串进行检查" 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

2 个答案:

答案 0 :(得分: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.");
    }
   }
 }
}

答案 1 :(得分:0)

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,直到他们输入有效的布尔值。然后它将突破循环,您可以继续使用其余的代码。