Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading