0

I am making a roll the dice game for a project I'm doing for school. I have a random Generator which is called via dice.rollDice() which then gives the result of the random number.

When I press a key the result of dice.rollDice is displayed on the console. I need to store the results in an array so far I have the array created

int[] randomNumbers = new int[7];

I'm not sure how to store the results of the dice.rollDice in the index I know to store an array the code is randomNumbers[] = dice.rollDice() is there a more efficient way to do this Any help is appreciated

Class Dice:

class Dice { 

    Random random = new Random(); // assigns random number generator Random();
    
    public int rollDice() {
        int output = 1 + random.nextInt(6); //returns a random number between 1 and 6
        return(output);
    }
}
Neuron
  • 5,141
  • 5
  • 38
  • 59

1 Answers1

1

I am answering your homework question because you have shown, that you have tried to solve it yourself. Please try to make sure you understand why this solves the problem.


You want several results, but your method only returns a single value. You can either embrace the fact that it it a single Die and call the function in a loop, or you can have your class represent multiple Dice. In the following I will show you how to implement the first approach:

class Die { // note, the singular of dice is "Die"
    private Random random = new Random();
    private int sideCount;

    public Die(int sideCount) {
        this.sideCount = sideCount;
    }

    public int roll() {
        int output = 1 + random.nextInt(sideCount); //returns a random number between 1 and sideCount
        return(output);
    }

    public int rollRepeatedly(int count) {
        int[] results = new int[count];
        // here we call the method we already have in a loop
        for (int i = 0; i < count; i++) {
            results[i] = roll();
        }
        return results;
    }
}

And now call your code like:

Die die = new Die(6);
randomNumbers[] = die.rollRepeatedly(7);

If you wanted to implement a class called Dice, it should have a constructor parameter counthave two options.

  1. Save the count parameter as a member variable. In your roll() method, create an array of results and fill it in a loop.

  2. Reuse the Die class by creating an array of Die in Dice, making it the size of count. Then roll them individually when calling dice.roll(). You could imagine how this array could even store Dies with different sideCounts, depending on the type of game you implement

Neuron
  • 5,141
  • 5
  • 38
  • 59