【问题标题】:Comparing two string arrays with a Nested For loops使用嵌套 For 循环比较两个字符串数组
【发布时间】:2013-04-05 13:43:10
【问题描述】:

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

我尝试使用

【问题讨论】:

  • cAnswers 和 rAnswers 中可能的值是什么?它似乎类似于 MCQ 类型的答案。如果是这样,一旦 cAnswers[i] 匹配了某些东西,你不应该从内部循环中跳出并转到下一个 cAnswers 吗?
  • 你的匹配项需要在同一个索引处还是无关紧要?

标签: java string for-loop arrays


【解决方案1】:

对于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]rAnswer 中的所有A's,将count 递增3。同样,对于cAnswer[2],它将再次匹配rAnswer 中的所有A's,从索引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);
    }
} 

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

【讨论】:

  • 嗨,我只想将 cAnswer[0] 与 rAnswer[0] 匹配。我认为我需要一个嵌套的 for 循环才能访问每个元素。你的答案已经足够了,它现在应该可以工作了。谢谢
【解决方案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");

【讨论】:

    【解决方案3】:

    不需要嵌套循环:

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 2016-01-23
      • 2023-03-25
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多