trying to write a program that casts a die 3 times and once you get 3 6s in a row it prints out how many tries it took. having a problem at the end of the code, the diff between || and &&, seems like it's the opposite, have a look...
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.
}
}
I believe your confusion comes forth from De Morgan's laws of negation. Basically, when you have a negation of a group of conditions, you should change &&
by ||
and vice versa when you negate the individual conditions.
Or simply put:
!(A && B) == !A || !B
!(A || B) == !A && !B
In you case, you want to do this:
!(array[0] == 6 && array[1] == 6 && array[2] == 6)
aka. "while it's not true that the first is 6 AND the second is 6 AND the third is six"
Due to the above law, in order to bring the !
inside, you need to change &&
for ||
, resulting in
!(array[0] == 6) || !(array[1] == 6) || !(array[2] == 6)
Simplified to
array[0] != 6 || array[1] != 6 || array[2] != 6