0

こんにちは、Java でクイズ プログラムを作成する際に問題が発生しています。私が抱えている問題は、ユーザーが最初の質問を正しく入力すると、2 番目の質問が表示されることです。ユーザーが 2 番目の質問に正しい答えを入力すると、次のようになります: a^2+b^2=c^2 、負けました。あなたのスコアは 1/10 のまま表示されます。」「正解!次の質問:」というはずですが、コーディングを始めたばかりなので、簡単な間違いでしたら申し訳ありません。

    import java.util.Scanner;

    public class Quiz {

public static void main(String[] args) {
    int Q1 = 0, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10 = 0;
    String Q2 = "";



    Scanner in = new Scanner(System.in);
    Scanner st = new Scanner(System.in);


    System.out.println("Welcome to the math quiz!, Type Reset at any time to start over");
    System.out.println("Q1: What is the square root of 9?");





        //beggining of questions:
    while (Q1 != 3) {
        Q1 = in.nextInt();
    if ( Q1 == 3) {
        System.out.println("Correct! Next Question:");
        System.out.println("Q2: What is pythagreoum's therom?");

    } else {
        System.out.println("Sorry, you lost, your score is 0/10");
    }
    }
  //end of Q1



    while (Q2 != "a^2+b^2=c^2" ) {
        Q2 = st.nextLine();
    if ( Q2 == "a^2+b^2=c^2" ) {
            System.out.println("Correct! Next Question:");  
    } 
    else {
        System.out.println("Sorry, you lost, your score is 1/10");
    }
    }

    //end of Q2 
            }
            }
4

4 に答える 4

0

比較中、演算子Stringsを使用するときは本当に注意する必要があります。比較される 2 つの文字列が両方とも同じである (つまり、同じ String オブジェクトである) 場合==にのみ返されます。trueを使用しQ2.equals("a^2+b^2=c^2")ます。==との違いの詳細については、こちらをお.equals読みください

于 2013-10-04T21:47:41.163 に答える
0

For Q2 it should read:

while (!Q2.equals("a^2+b^2=c^2")) {
    Q2 = st.nextLine();
    if (Q2.equals("a^2+b^2=c^2")) {
        System.out.println("Correct! Next Question:");
    } else {
        System.out.println("Sorry, you lost, your score is 1/10");
    }
}

Don't use "==" to compare two Strings.

于 2013-10-04T21:48:30.617 に答える