Ernest Friedman-Hill wrote:Hi Jason,
I'm not sure I follow what you're trying to do, but wouldn't it make more sense to simply generate numbers and check if they're in the arraylist first, before adding them?
Finally, note that "contains()" is expensive when called on a long list -- it has to look at each item in the list one at a time. Sets like HashSet or TreeSet are much better at checking for a value, and they do it automatically -- a Set, by definition, can't contain duplicates. So you could simplify this further by adding random numbers to a HashSet until it was the right size, and then constructing an ArrayList to contain the result. It's just a few lines of code, but I'll leave it up to you.
I decided to go back to the drawing board with
Java and start from the beginning again to re-learn everything. When I originally created this program I used Swing elements to draw a GUI but couldn't get the ScoreBoard panel to update after pressing play (everything else worked behind the scenes except for that).
The game starts by asking for 10 numbers, gets those numbers, checks for duplicates, shows them to the player, then asks for P to play Q to quit. After pressing "P" I had the code I provided that was
supposed to: generate a random number, check for duplicates, then display them to the user. The program shows the number of matches to the user and which numbers actually matched up. That's it.
That is exactly what I was trying to do! I don't know anything about HashSets or TreeSets yet (although I have heard of HashSets) but I will look into those.
Why I wrote the code I wrote:
1. The for loop was to fill the arraylist with random numbers
2. The second for loop was supposed to cycle through the array and check if that newly created element was already used.
-- I see where I went wrong here. I'm not sure why I didn't see that when I was going over it, I'm still new to all this. Of coarse it is going to contain that number because it just created it
3. Remove the element if it was a duplicate
4. Create a new random number.
**NOTE
This was something I had already wrote and had working with normal arrays, but I wanted to move on try to use ArrayLists. To be honest, I'm not sure how I had this working with regular arrays (I started over from scratch) but somehow it was. Or perhaps, I was just getting lucky with my generated numbers.
Either way, thanks again for the input.
You guys/gals are great, as always.