The condition in my while loop doesn’t seem to be correct?… here is a solution to the problem.
The condition in my while loop doesn’t seem to be correct?
Try to write a program, throw 3 dice and once you get 3 6s in a row, it prints out how many attempts have been made. There is a problem at the end of the code, || The difference between &&&, as if the opposite, see….
package javaapplication12;
import java.util.*;
public class JavaApplication12 {
public static void main(String[] args) {
Random rand = new Random();
this should try to cast a die 3 times and keep doing that until we get 3 6s in a row and counter
how many tries it takes to get that.
int array[] = new int[3]; creating 3 places for castin our die 3 times in a row
int counter1 = 0; creating a counter to track each time we try to cast 3 die ( 3 cast = 1 try)
do{
counter1++;
System.out.println("try " + counter1); prints out counter in the beginning of every try.
for (int counter = 0; counter < array.length; counter++ ){
array[counter]=(rand.nextInt(6)+1); a loop that fills the array with random numbers from 1-6
}
for(int x: array)
{System.out.println(x); } // this is for our own to check if we have 3 6s in a row,
prints out all the numbers in out array
}
so this is the I'veusing part, i've written 3 scenarios that can be written for the condtion in our
do- while loop...
while (array[0]+array[1]+array[2] != 18); this works just fine.
while (array[0] !=6 || array[1] != 6 || array[2] != 6); imo this should not work but surprisingly it does
while (array[0] !=6 && array[1] != 6 && array[2] != 6); this should work, but it doesnt.
}
}
Solution
I believe your confusion comes from De Morgan’s laws of negation &&
changes to ||
and vice versa when you reject a single condition.
Or simply:
!( A && B) == ! A || ! B
! (A || B) == ! A && ! B
In your case, you want to do this:
!( array[0] == 6 && array[1] == 6 && array[2] == 6)
a.k.a. “Although the first is 6, the second is 6, and the third is 6 is incorrect”
Due to the above law, in order to put !
Bring in, you need to change &&&
s to ||
, leading
!( array[0] == 6) || ! (array[1] == 6) || ! (array[2] == 6)
Simplified to
array[0] != 6 || array[1] != 6 || array[2] != 6