Question:
How to loop in Java with multiple conditions?
MGSGreyF0x
2013-10-08 21:13:47 UTC
So, this program rolls two dice. I want it to loop forever until it hits a double 6. Here is the code I have right now, and I can't figure out why its not working.

import java.util.*;
public class Lab05_ex2
{
public static void main(String[] args)
{
Random dieTosser = new Random();

int die_1;
int die_2;
do
{
die_1 = dieTosser.nextInt(6) + 1;
die_2 = dieTosser.nextInt(6) + 1;
System.out.println(die_1 + " : " + die_2 );
} while ( die_1 != 6 ) && ( die_2 != 6);
}
}
Three answers:
AnalProgrammer
2013-10-08 21:16:41 UTC
Try

} while ( (die_1 != 6 ) && ( die_2 != 6) );



Have fun.
?
2013-10-08 21:27:18 UTC
You got to do two things

1. In the while statement, enclose all that follows in braces

2. Change the condition from && to ||

So your final statement should be



while (( die_1 != 6 ) || ( die_2 != 6));



this happens because, in what you have written, as soon as even one of die_1 or die_2 becomes 6, the condition becomes false and the loop terminates. But, what you need is only when both the conditions become false, the loop should terminate. So you gotta use ||.
2013-10-09 01:38:24 UTC
Try this condition while ( (die_1 + die_2 < 12 )


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...