Andrés Bustamante Andrés Bustamante - 1 month ago 16
Java Question

My dice roll generator is not working as expected

I'm trying to simulate a dice roll in Java, but my code is not working.

Dice:

import java.util.Random;

public class Dice implements DiceOperations {
int value;
static int FACES = 6;

public void roll() {
Random rnd = new Random();
value = rnd.nextInt(FACES) + 1;
}

public int getValue() {
return value;
}
}


Dice operations:

public interface DiceOperations {
public abstract void roll();
public abstract int getValue();
}


Play:

public class Play {
public static void main(String[] args) {

int[] results = new int[6];

System.out.println("¿How many rolls?");
int n = Integer.parseInt(System.console().readLine());

for (int i=0; i<n; i++){

dice.roll();
results[dice.getValue() - 1] = results[dice.getValue() - 1]+1;
}

System.out.println("The numbre one got: "+results[0]);
System.out.println("The numbre two got: "+results[1]);
System.out.println("The numbre three got: "+results[2]);
System.out.println("The numbre four got: "+results[3]);
System.out.println("The numbre five got: "+results[4]);
System.out.println("The numbre six got: "+results[5]);

}
}

Answer

I believe that all your functions are right but the problem is that you're not initializing the object dice in your main so you may try to put this on your code:

Dice dice = new Dice();

So your main will be something like this:

public class Play {
  public static void main(String[] args) {

    int[] results = new int[6];

    System.out.println("¿How many rolls?");
    int n = Integer.parseInt(System.console().readLine());
    Dice dice = new Dice();

    for (int i=0; i<n; i++){

        dice.roll();
        results[dice.getValue() - 1] = results[dice.getValue() - 1]+1;
    }

    System.out.println("The numbre one got: "+results[0]);
    System.out.println("The numbre two got: "+results[1]);
    System.out.println("The numbre three got: "+results[2]);
    System.out.println("The numbre four got: "+results[3]);
    System.out.println("The numbre five got: "+results[4]);
    System.out.println("The numbre six got: "+results[5]);

  }
}