用户输入字符串时出现问题(Java)

时间:2019-06-06 18:12:15

标签: java

我有一系列问题和一系列对应的答案。我让用户回答问题,然后使用if语句将答案与实际答案进行比较。即使答案是正确的,它仍将输出显示为不正确。请帮忙。

扫描仪输入=新的扫描仪(System.in);

    int inputOne;
    int inputTwo;

    String answer1, answer2, answer3, answer4, answer5, answer6, answer7, answer8, answer9, answer10, answer11, answer12;


    String[] questions = {"How many continents are there?", "What is the capital of Canada?", "What is the largest country in the world?", "What is the largest ocean in the world?", "How many oceans are there in the world?", "How many countries make up Africa?", "How many countries in the world begin with the word United?", "Where is Milan?", "What is the least populated US state?", "What is the capital of Australia?", "How many countries begin with the letter J?", "Which country has the most lakes in the world?"};                                                                                                                                                                                                                                                                                          //

    String[] answers = {"7", "Ottawa", "Russia", "Pacific", "5", "54", "3", "Italy", "Wyoming", "Canberra", "3", "Finland"};                                                                                                            





    System.out.println("Enter the row and column: ");

    inputOne=input.nextInt();
    inputTwo=input.nextInt();



    if (inputOne < 0 || inputTwo < 0 || inputOne > 2 || inputTwo > 3) {
        System.err.println("Invalid input. Input a number between 0 - 2 for the row, and a number between 0 - 3 for the column.");
    }   

    if (inputOne == 0 && inputTwo == 0) {
        System.out.println("You chose 500.");
        System.out.println(questions[11]);
        answer1=input.next();
        if (answer1 == answers[11]) {
            System.out.println("Correct!");
        }
        else {
            System.err.println("Wrong.");
        }
    }

1 个答案:

答案 0 :(得分:0)

如果字符串相等,则要使用

str1.equals(str2);

使用==检查两个变量是否都指向相同的存储位置。另外,最好使用“问题字典”和“答案类型问题”,其中问题是关键,答案是值。