比较两个字符串数组与嵌套For循环

时间:2013-04-12 21:45:47

标签: java string for-loop arrays

您好我正在尝试使用嵌套for循环找到两个字符串数组之间的匹配项。然而,它似乎已经循环了很多次。

for(int i = 0; i < ca; i++) //ca contains 10
{
    for(int j = 0; j < ra; j++) //ra contains 10
    {
        if(cAnswers[i].equals(rAnswers[j]))
        {
            count++; //Increments count to indicate a match
            System.out.println("The current count: " + count); //To check the count
        }
    }
}
System.out.println("The number of correct questions is " + count + "/10"); //The result currently gives me 50/10 no matter what.

我尝试使用&lt; =而不仅仅是&lt;但最终导致索引超出范围。

3 个答案:

答案 0 :(得分:4)

对于cAnswer中的每个答案,您都会查看rAnswer中的所有答案。

String rAnswer[] = {"A", "B", "A", "D", "A", "F", "G", "H", "I", "J"};

并且

String cAnswer[] = {"A", "B", "A", "D", "A", "F", "G", "A", "I", "A"};

它会将cAnswer[0]A's中的所有rAnswer相匹配,将count增加3.同样,对于cAnswer[2],它将再次匹配所有A'srAnswer从索引0开始。这是你想要的吗?

如果你想进行线性匹配,即cAnswer[0]rAnswer[0]一个循环就足够了。

for(int i = 0; i < cAnswers.length && i < rAnswers.length; i++)
{
    if(cAnswers[i].equals(rAnswers[i]))
    {
        count++; //Increments count to indicate a match
        System.out.println("The current count: " + count);
    }
} 

如果您想做其他事情,请通过提供更多详细信息来帮助我们。

答案 1 :(得分:2)

更好的解决方案:

Set<String> set = new HashSet<>(Arrays.asList(cAnswers));
set.retainAll(Arrays.asList(rAnswers));
System.out.println("The number of correct questions is " + set.size() + "/10");

答案 2 :(得分:0)

不需要嵌套循环:

for(int i = 0; i < cAnswers.length && i < rAnswers.length; i++)
{
    if(cAnswers[i].equals(rAnswers[i]))
    {                           // ^
        count++; //Increments count to indicate a match
        System.out.println("The current count: " + count);
    }
}