将实际输入值存储到数组中以与另一个数组进行比较

时间:2013-06-11 16:32:37

标签: java arrays

我还是Java新手。我正在尝试创建一个用户必须回答多项选择测验的程序。用户将输入他们的答案,这些输入将形成一个数组。然后我计划使用for循环将用户的答案数组与正确答案数组进行比较,告诉用户他们是对还是错。

然而,似乎我没有正确比较我的if语句中的2个数组。每次我运行程序时,都会直接进入else语句。

我的预感是扫描仪类实际上并不存储值?

有人可以帮忙吗?

以下部分代码:

//Above this section is just a collection of "System.out.println" statements that state questions and answers the user choose from.




     int x;
                String answers [] = {"a", "a", "b"}; 
    //answers array has the correct answer 
                Scanner in = new Scanner(System.in);
                String answerEntered [] = new String [5]; 
    //user input will be in this arra

                for(x=0 ; x<3 ; x++)
                {
                    System.out.print((1+x)+". ");
                    answerEntered[x] = in.nextLine();
                }
                for( x=0; x<3; x++)
                {   

                    **if(answerEntered[x] == answers[x])
                    {
                        System.out.println("For Question "+(x+1)+", you are Correct!");
                    }**
     //This if section does not seem to work. Every time i run the code it automatically goes to the else statement. 

                    else
                    {
                        System.out.println("The correct answer for Question "+(x+1)+" is: "+answers[x]);
                    }
                }

6 个答案:

答案 0 :(得分:4)

在Java中,String不是原始值,您必须使用String.equals()来比较字符串 所以,改变这个:

if(answerEntered[x] == answers[x])

if(answerEntered[x].equals(answers[x]))

我还建议您检查可空性并忽略大小写,所以:

String answer = answerEntered[x];
boolean isAnswerCorrect = 
        answer != null && 
            //remove trailling spaces and ignore case (a==A)
        answer.trim().equalsIgnoreCase(answers[x]);
if(isAnswerCorrect){

答案 1 :(得分:1)

对于String比较,您需要使用equals而不是==,对于非原始数据类型(例如String),它们会比较它们的引用,而不是值

String a = "foo";
String b = "bar";

if (a.equals(b))
{
    //doSomething
}

答案 2 :(得分:1)

对于String或Java中的任何对象相等性测试,您几乎应该始终使用equals==运算符仅在与对象一起使用时比较引用(但将按照您对intboolean等原语的预期方式工作;也就是说,它检查操作数是否指向/引用同一个对象实例。您有兴趣做的是比较String个实例的内容,而equals会为您做到这一点:

if(answerEntered[x].equals(answers[x])) {
   ...
}

答案 3 :(得分:1)

问题在于比较:

String a = "foo";
String b = "bar";

if (a.equals(b))
    //doSomething

之前已经回答过。

额外的信息,在if / else的for循环中,你只循环前3个位置,而不是answerEntered数组中存在的5个位置。

干杯

答案 4 :(得分:0)

使用.equals来比较字符串。 equals比较值,==比较参考值 。

答案 5 :(得分:0)

在Java中,==比较引用标识,意味着你比较的两件事必须是同一个对象。具有相同值的两个对象被视为不同。

你声明:

if(answerEntered[x] == answers[x])

answerEntered包含与答案中的任何字符串不同的字符串,即使它们具有相同的值。

Java使用Object的.equals方法按值进行比较,即两个对象相等,只要它们具有相同的值即可。

更改:

if(answerEntered[x] == answers[x])

if(answerEntered[x].equals(answers[x])) 

应该解决问题。

此外,由于answerEntered包含用户输入值,因此您最好在使用前对其进行预处理。例如,用户可能会在末尾添加带空格的答案“a”。您可能也希望摆脱这些空间。

否则“a”将被视为错误答案。

相关问题