-1

I created a GUI that will be 10 x 10 and have 100 buttons. I had to insert 20 treasures and have the other 80 be empty. This is the code I used. Sometimes I get 17 treasures, sometimes 18, sometimes 19. How do I fix this?

Thank you in advance.

Random random = new Random();
        for (int index = 0; index < 20; index++)
        {
            int insertionIndex = random.nextInt(99)+1;
            buttonGrid[insertionIndex] = new TreasureButton(treasureGame, this);
        }
        // Loop to add EmptyButton()'s into remaining null indexes within the buttonGrid
        for (int index = 0; index < 100; index++)
        {
            // if the current index is null, add an EmptyButton() into it
            if (buttonGrid[index] == null)
            {
                buttonGrid[index] = new EmptyButton(treasureGame, this);
            }
        }
        // Loop to add all of the contents of the buttonGrid into the gamePanel
        for (int index = 0; index < 100; index++)
        {
            gridPanel.add(buttonGrid[index]);
        }
camickr
  • 321,443
  • 19
  • 166
  • 288
Suz Renae
  • 19
  • 4
  • Why do you say there aren't 20? How would you tell if there were multiple on the same square? – geocodezip Nov 30 '20 at 02:53
  • I did not realize that there can be multiple in the same square. I have created a 10 x 10 grid and each time I click the square to uncover it, a "$" will appear if it is a treasure. Is there a way to make sure that there is only 20 treasures in different squares in the grid? – Suz Renae Nov 30 '20 at 03:00
  • Why are you asking this question again? The suggestion in your last question: https://stackoverflow.com/questions/64952221/creating-a-grid-layout-that-holds-100-buttons-with-80-empty-buttons-and-20-rando, what to also use the Collections.shuffle(...). – camickr Nov 30 '20 at 03:45
  • Why use ``nextInt(99) + 1`` rather than ``nextInt(100)``? – NomadMaker Nov 30 '20 at 06:05
  • I am very new to Java and I apologize for not entirely understanding and for asking similar questions. I will continue working on this. – Suz Renae Nov 30 '20 at 06:13

1 Answers1

3
  1. Create an ArrayList
  2. Add 20 TreasureButton instances to the ArrayList
  3. Add 80 EmptyButton instances to the ArrayList
  4. Use Collections.shuffle(...) to randomize the buttons.
  5. Iterate through the ArrayList and add each button to the panel
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Is there any way to keep the code I have and make it work? – Suz Renae Nov 30 '20 at 03:23
  • 2
    When you use the Random class you can't force it to generate 20 unique numbers. The point is the number is random, so the same number can be repeated. I provided a simple approach to ensure that your grid will contain exactly 20 randomized Treasure buttons. If you think you need your buttons in an Array, then copy the buttons to the Array at the same time you add them to the panel. – camickr Nov 30 '20 at 03:36