Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Java , ArrayList comparison trouble?

So I am trying to compare two arrays and add the matching numbers to a third array. I keep getting OutOfBoundsException, but the program so far seems to work like it should. I just need to make a decision structure to see how many matching numbers there are and tell if the user wins something for geussing all the right numbers.

public ArrayList<Integer> compare(ArrayList<Integer> user) //user is an array being passed from main

{

ArrayList<Integer> match = new ArrayList<>();

for(int i = 0; i < user.size(); i++)

{

for( int c = 0; c < lotteryNumbers.size(); c++)

if(user.get(i)==lotteryNumbers.get(c))

{

match.add(lotteryNumbers.get(c));

System.out.print(match.get(c) + ", ");

}

}

// System.out.println(match);

return match;

}

Update:

Using David's suggestion, the program just prints out the user selected numbers, not the new match array.

1 Answer

Relevance
  • david
    Lv 7
    6 years ago

    System.out.print(match.get(c) + ", ");

    This is likely the line where the error is happening. c is the counter for the lotteryNumbers list, not a counter for the match list. If the first lottery number isn't a match and you go to the second one, then match.get(c) will fail because it's trying to get the second number in the "match" list but there's only one number in there.

    Try this instead:

    System.out.print(lotteryNumbers.get(c) + ", ");

    I think this will be the number you want.

Still have questions? Get your answers by asking now.