can't figure out the right way to make this decision

2448 views java
0

I'm working on coding a dice game and don't know where to go next. This is the code i have

total = roll();

if(total == 9 || total == 11 || total == 18 || total == 24)
{   
    System.out.println("You win");
}else if(total == 6 || total == 12 || total == 13 || total == 17 || total == 19 || total == 23 )
{
    System.out.println("You lose");
}else
{
    int gn = total;
    System.out.println("You goal number is now " + gn);

    do{
        roll = roll();

    }while(roll != gn);

    System.out.println("You win");

}

public static int roll()
{
    Random rand = new Random();

    int die1 = rand.nextInt(6) + 1;
    int die2 = rand.nextInt(6) + 1;
    int die3 = rand.nextInt(6) + 1;
    int die4 = rand.nextInt(6) + 1;
    int total = die1 + die2 + die3 + die4;

    System.out.println("You rolled " + total);

    return total;
}

If the user doesn’t roll a winning number (9, 11, 18 or 24) or losing number (6, 12, 13, 17, 19, or 23) then that number becomes your goal and you have to roll until you get that number again or until you roll a 13 and lose.

I have it working until the goal number is reached, but i do not know how to make it stop if a 13 is rolled.

answered question

2 Answers

8

do / while loops have a continuation condition. Currently, your loop would continue until the total is reached, at which point the user wins:

do {
    roll = roll();
} while(roll != gn);

To deal with hard-coded 13, add && roll != 13 to the continuation condition:

do {
    roll = roll();
} while(roll != gn && roll != 13);

However, now your need to figure out why the loop has finished - because of a win, or because of a loss. You can compare roll to 13 outside the loop in a condition to make that decision:

System.out.println("You " + (roll != 13 ? "win" : "lose"));

posted this
0

do {
    roll = roll();
} while(roll != gn && roll != 13);

System.out.println("You " + (roll == 13)?"lose":"win");

posted this

Have an answer?

JD

Please login first before posting an answer.