简体   繁体   中英

Comparing two string arrays with a Nested For loops

Hi I'm trying to find matches between two string array using a nested for loops. However it seem to have looped around more times.

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.

I tried using <= instead of just < but end up getting a index out of bounds.

For every answer in cAnswer , you are going over all the answers in rAnswer .

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

And

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

It will match cAnswer[0] with all A's in rAnswer , incrementing count by 3. Similarly, for cAnswer[2] it will again match all A's in rAnswer starting from index 0. Is this what you want?

If you want to do a linear match, ie cAnswer[0] with rAnswer[0] a single loop is sufficient..

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

If you want to do something else, help us help you by providing more details.

A nicer solution:

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

Don't need nested loops for that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM