匹配2个问题和答案的arraylists在java中的测验游戏

时间:2014-01-17 05:55:17

标签: java string if-statement arraylist

我正在使用netbeans在java中进行测验游戏。我为我的所有问题制作了一个数组列表,并为我的答案制作了另一个数组列表。我把它们都按顺序排列(比如第一个是安大略省的首都......在答案列表中,第一个是多伦多。 ..所以他们都匹配了)

我这样做是为了随机生成一个问题...但现在我必须让它与答案相匹配....并检查用户的输入是否与答案匹配。这是我尝试过但它无法工作:

String input = inputTextField.getText();
String output = "";
questions = answers -------> Those are the names of my 2 array lists

if (input = answers) {
output = "Congratulations";
}
else if (input != answers) {
 output = "You got the question wrong";
}

**请帮忙......我也是初学者,谢谢你:)。

4 个答案:

答案 0 :(得分:1)

您需要使用contains方法检查ArrayList是否包含问题和答案。

ArrayList<String> questions = new ArrayList<String>();
ArrayList<String> answers = new ArrayList<String>();

questions.add("What is you name?");
answers.add("My answer here");

String inputQuestion ="GET_QUESTION_FROM_TEXTFIELD_HERE";
String inputAnswer ="GET_ANSWER_FROM_TEXTFIELD_HERE";

String output = "";

if(questions.contains(inputQuestion))
{
    if(inputAnswer.equals(answers.get(questions.indexOf(inputQuestion))))
        output = "Congratulations";
    else
        output = "Worng answer";
}
else
    output = "You got the question wrong";

答案 1 :(得分:1)

最好为java.util.Map<String, String>对使用< question, answer >而不是2个列表。这样你就可以确定答案对你的问题是否正确。

更高级,您甚至可以执行此操作Map<String, List<String>>,而且一个问题的答案可能不止一个。

答案 2 :(得分:0)

如果answersArrayList,那么您的if条件应为

if (answers.contains(input)) {
    output = "Congratulations";
}

答案 3 :(得分:0)

创建一个包含问题和答案的新对象并将其放入列表中。然后从该列表中随机获取一个对象并从该对象发布问题。然后获取输入并检查该对象的答案是否等于该对象中的答案。干杯!

public class test {


    public static void main(String[] args) {
        ArrayList<QandA> QandAnswerCntainer = new ArrayList<QandA>();
        QandAnswerCntainer.add(new QandA("What is biggest flower","ROSE"));
        QandAnswerCntainer.add(new QandA("What is biggest ship","test"));

        Random r = new Random();
        int randomQ = r.nextInt(2);
        QandA testQuestionAndAnswer = QandAnswerCntainer.get(randomQ);

        System.out.println(testQuestionAndAnswer.getQuestion());

        //get the answer to the string using your input . I will make a demo answer
        String answer = "test"; // answer got from your input method

        if (answer.equals(testQuestionAndAnswer.getAnswer())){
            System.out.println("correct");
        }
        else {
            System.out.println("wrong");
        }




    }
}

class QandA{

    private String question;
    private String answer;

    QandA(String question,String answer){
        this.answer = answer;
        this.question = question;
    }


    public String getQuestion() {
        return question;
    }

    public String getAnswer() {
        return answer;
    }
}