-1

私は現在、基本的な Java クラスを受講している学生です。私は、ユーザーにゲームの「開始」と「終了」の入力を求めるコードに取り組んでいます。すっごく私はそれぞれ文字列「S」と「Q」を選びました。ユーザーが S を入力すると、ゲームが進行します。ユーザーが Q を入力すると、プログラムは「遊んでくれてありがとう」か何かを表示します。ユーザーが S と Q 以外の何かを入力すると、プログラムは有効な入力が得られるまで再度尋ねます。エラーチェックの部分を除いて、ほぼすべて正しく取得できましたコードを修正するための提案はありますか?

前もって感謝します!:)

(部分コード)

    Scanner scan = new Scanner(System.in);
    String userInput;
    boolean game = false;

    System.out.println("Welcome to the Game! ");
    System.out.println("Press S to Start or Q to Quit");

    userInput = scan.nextLine();

    if (userInput.equals("S")){
        game = true;
    } else if (userInput.equals("Q")){
        game = false;
    } else {
        do {
            System.out.println("Invalid input! Enter a valid input: ");
            userInput = scan.nextLine();
        } while (!"S".equals(userInput)) || (!"Q".equals(userInput)); // I'm not sure if this is valid???
    }

    if (userInput.equals("S")){
        ///// Insert main code for the game here////
    } else if (userInput.equals("Q")){
    System.out.println("Thank you for playing!");
    }
4

2 に答える 2

2

無限ループを作成しています:

while (!"S".equals(userInput)) || (!"Q".equals(userInput)); // always true

この条件が成立しないためには、等しい入力と一緒に入力する必要が"S" あり"Q"ます。De-Morgan の法則を適用するのは簡単です。

while (!("S".equals(userInput)) && "Q".equals(userInput))); // always true

明らかに、それは起こりません。

あなたはおそらく欲しい:

while (!"S".equals(userInput)) && (!"Q".equals(userInput));
于 2016-07-23T13:26:36.403 に答える