Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Math.Random loop until specific number is reached

I'm trying to make a program that 'rolls two dice' and combines the number and needs to keep going until a specific number is reached 7 or 11 but every time I run it it keeps going forever.

double total = 0;
while (total != 7 || total != 11) {
    DecimalFormat x = new DecimalFormat("#");
    double dice1 = Math.random() * 6 + 1;
    double dice2 = Math.random() * 6 + 1;
    double total = (dice1 + dice2);
    System.out.println("Dice 1: " + x.format(dice1) + " Dice 2: " + x.format(dice2) + " Total: " + x.format(total));

    }

I think its because the int total is set to 0 and isn't getting the total from the loop but how can i fix this?

like image 650
Taj Melic Avatar asked Jun 12 '26 22:06

Taj Melic


2 Answers

Your while loop logic is not correct. The total will always not be 7 or not be 11. You want "and" instead, using &&. Change

while (total != 7 || total != 11) {

to

while (total != 7 && total != 11) {

Also, I don't know of any dice that yield non-integers, so I would cast the results to int and declare dice1, dice2, and total as ints.

like image 196
rgettman Avatar answered Jun 14 '26 10:06

rgettman


It's because you shadow total and you need to test logical and (not or). I would also prefer to use Random and nextInt(int) like

int total = 0; // <-- don't shadow me.
Random rand = new Random(); 
while (total != 7 && total != 11) {
  int dice1 = rand.nextInt(6) + 1; // <-- using rand.
  int dice2 = rand.nextInt(6) + 1;
  total = (dice1 + dice2); // <-- no double.
  System.out.printf("Dice 1: %d Dice 2: %d Total: %d%n", dice1, dice2, total);
}
like image 22
Elliott Frisch Avatar answered Jun 14 '26 11:06

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!