ChrisW91
ChrisW91

Reputation: 55

Returning a variable from nested for loops

I am writing a lottery class, and the rest of my code is working except for the method which compares the amount of matching lottery numbers. I can't figure out for the life of me how to keep a count of the matches AND return it.

I'm fairly new to java so I apologize if this is a blatantly obvious answer.

Here is the code for the method I am working with:

public int numIntsInCommon(int[] picks){
     int inCommon = 0;

     for (int counter = 0; counter < 5; counter++)
     {
        for (int index = 0; index < 5; index++)
        {
           if (lotteryNumbers[counter] == picks[index])
              inCommon += 1;

        }
        return inCommon;
     }

     return inCommon;
  }

Right now it currently only returns 0. Any help would be greatly appreciated! Thanks

Upvotes: 1

Views: 7696

Answers (5)

Andrii Polunin
Andrii Polunin

Reputation: 1306

If you use Java Collections Framework and define your lotteryNumbers and picks as List then your problem is much easier to solve, something like this:

public int numIntsInCommon(List<Integer> picks) {
    List<Integer> matches = new ArrayList<Integer>(picks);
    matches.retainAll(lotteryNumbers);
    return matches.size();
}

Upvotes: 0

Ariel Grabijas
Ariel Grabijas

Reputation: 1512

public int numIntsInCommon(int[] picks)
{
     int inCommon = 0;

     for (int counter = 0; counter < 5; counter++)
     {
        for (int index = 0; index < 5; index++)
        {
           if (lotteryNumbers[counter] == picks[index])
              inCommon++;
        }
     }

     return inCommon;
}

Should be fine now. What you have done before, was jump out of the nested loops after first iteration. In other words: thanks to your nested return, the loop ended after counter = 1.

Upvotes: 1

Junfei Wang
Junfei Wang

Reputation: 578

In java, "return" means termination of a function, so if your return in inner loop, the outer loop will never be executed in any case.

Upvotes: 1

EMMERICH
EMMERICH

Reputation: 3474

The first return statement will return the inCommon value before the method has had chance to complete the outer loop. I'm not sure the point of that first return statement at all, really.

Upvotes: 2

BlackVegetable
BlackVegetable

Reputation: 13064

Remove the return inCommon from the for loop. The outer return is never being reached.

Upvotes: 2

Related Questions