1

您好我正在尝试使用嵌套的 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.

我尝试使用 <= 而不仅仅是 < 但最终使索引超出范围。

4

3 回答 3

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]与 all A'sin匹配rAnswer,递增count3。同样,cAnswer[2]它将再次从索引 0 开始匹配 all A'sin rAnswer。这是您想要的吗?

如果你想做一个线性匹配,即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);
    }
} 

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

于 2013-04-12T21:55:59.670 回答
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");
于 2013-04-12T22:04:54.600 回答
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);
    }
}
于 2013-04-12T21:48:18.230 回答