-1

I need to store a random number into an array and then be able to compare the array sums at a later time. So far I have this:

public class Die {
    private int dieValue = 0;
    private Random randomNumbers = new Random();
    public Die() {
}

public void rollDie() {
    dieValue = randomNumbers.nextInt(6*1);
}
public void displayDie() {
    int[] die = new int[3];
    for(int counter = 0; counter<die.length; counter++ ) {
        rollDie();
        die[counter] = dieValue;
    }
    System.out.print("Your Dies are: " + die[1] + " and " + die[2] + " and " 
    + die[3]);
    dieValue = die[1] + die[2] + die[3];
}

This gives me an error saying the array index is out of bounds, and i'm not sure how to properly code this.. any tips would be great!

  • 1
    Possible duplicate of [Why does an array index or base index start with 0?](https://stackoverflow.com/questions/41530124/why-does-an-array-index-or-base-index-start-with-0) – Stewart Apr 04 '18 at 22:34

4 Answers4

1

In Java, arrays start at index 0, so an array of size 3 (like you've made) will have indices 0,1,2. The out of bounds is because you're trying to used indices 1,2,3 (3 does not exist).

Also, you're saying that you need to access the values at a later time, so you should probably declare the array outwith the method, so that it persists after the method finishes (just now, due to the scope of the variable, it will disappear after displayDie() finishes.)

Sean
  • 212
  • 1
  • 10
1

When you are trying to access the first value stored in an array the index should be 0, in you code above you try to access the 3 values as die[1], die[2], and die[3], but you need to be accessing them as die[0], die[1], and die[2].

Domin Sweet
  • 117
  • 4
1

Indexes for the die array in the displayDie() method are off, array index in Java starts from 0. First value will be die[0] instead of die[1].

0

Last line you have

dieValue = die[1] + die[2] + die[3];

and suppose to be

dieValue = die[0] + die[1] + die[2];

because there's not die[3] that's why you get the error

What you can do and will be better to loop the array

for(int i=0; i< die.length; i++){
   dieValue +=die[i];
}
mooga
  • 3,136
  • 4
  • 23
  • 38