2013-04-12 136 views
1

嗨我試圖找到使用嵌套for循環兩個字符串數組之間的匹配。然而它似乎已經環繞了更多次。比較兩個字符串數組與嵌套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. 

我嘗試使用< =,而不是僅僅<,但最終得到一個索引越界。

+0

什麼是cAnswers和rAnswers的可能值?這似乎與MCQ類型的答案類似。如果是這樣,一旦cAnswers [i]匹配一些東西,你不應該從內部循環中跳出來並轉到下一個cAnswers? – devang

+0

你的比賽是否需要在同一個索引或無所謂? – jlordo

回答

3

對於每一個答案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,由3遞增count同樣,對於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); 
    } 
} 

如果你想別的做一些事情,幫助我們提供更多的細節幫助你。

+0

嗨,我只想匹配cAnswer [0]和rAnswer [0]。我以爲我需要一個嵌套的循環才能訪問每個元素。您的答案足夠了,它現在可以正常工作。謝謝 – user1832478

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