Search code examples
javainstancedice

Dice Roller Values


I am creating a dice rolling application with java. I have a "Die" class that rolls a single die, and a "Dice" class that uses multiple instance variable of "die". However, it only returns 0 for my values. The Die class on its own works and will roll a random number, but I can not figure out how to get multiple rolls in my "Dice" class. Any help is appreciated.

Dice Class

public class Dice {
    Die die1=new Die();
    Die die2=new Die();
    private int die1Value;
    private int die2Value;
    private int sum;
    public Dice() {
        die1Value=0;
        die2Value=0;
    }
    public int getDie1Value() {
        return die1Value;
    }
    public int getDie2Value() {
        return die2Value;
    }
    public int getSum() {
        return sum;
    }
    public void roll() {
        die1Value=die1.getValue();
        die2Value=die2.getValue();
        sum=die1Value+die2Value;
    }
    public void printRoll() {
        System.out.println("Die 1: "+die1Value);
        System.out.println("Die 2: "+die2Value);
        System.out.println("Total: "+sum);
        if (sum==7) {
            System.out.println("Craps!");
        } else if (die1Value==1 && die2Value==1) {
            System.out.println("Snake Eyes!");
        } else if (die1Value==6 && die2Value==6) {
            System.out.println("Box Cars!");
        } else {
            System.out.println();
        }
    }
}

Die Class

package a3.ben;

public class Die {
    private int value;
    public Die() {

    }
    public void roll() {
        value=(int) (Math.random()*6)+1;
    }
    public int getValue() {
        return value;
    }
}

Solution

  • You never call die.roll. Try changing the roll method in Dice to include rolling both dice before getting their values.

    public void roll() {
        die1.roll(); // change the value of both dice
        die2.roll();
        die1Value = die1.getValue();
        die2Value = die2.getValue();
        sum = die1Value + die2Value;
    }
    

    Also added some spaces around operators like = and + for readability