[英]the condition in my while loop doesn't seem right?
尝试编写一个将骰子投放3次的程序,一旦连续获得3个6s,它就会打印出需要尝试的次数。 在代码末尾有问题,||之间的差异 和&&似乎相反,看看...
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.
}
}
我相信您的困惑来自De Morgan的定律 。 基本上,当您否定一组条件时,应通过||
更改&&
。 否定各个条件时,反之亦然。
或简单地说:
!(A && B) == !A || !B
!(A || B) == !A && !B
在这种情况下,您想这样做:
!(array[0] == 6 && array[1] == 6 && array[2] == 6)
又名。 “虽然第一个是6,第二个是6,第三个是6,这不是真的”
由于上述法律,为了带来!
在里面,您需要更改&&
为||
, 导致
!(array[0] == 6) || !(array[1] == 6) || !(array[2] == 6)
简化为
array[0] != 6 || array[1] != 6 || array[2] != 6
您的第一个条件是:总和不是18,因此确实应该正确运行。
第二个条件是:至少一个骰子不是6,所以它也应该正常工作。
您的最后一个条件:没有骰子是6,所以即使单个骰子滚动6,它也将断裂,因此这是行不通的。
更新:AND(&&)表示参数的两面都必须为真,才能使输出为真; OR(||)表示参数的一面必须为真,以使结果为真。
您需要重新研究布尔代数的基本运算。
那应该是这样的。 这个:
do{
}while(array[0] !=6 && array[1] != 6 && array[2] != 6)
意味着只要条件为真,循环就会继续。 换句话说,如果将任一部分评估为false,则循环将停止。 因此,如果array[0]==6
则循环将中断。
while (array[0] !=6 || array[1] != 6 || array[2] != 6);
这很好,因为它的意思是:“虽然三个尝试之一不是6”
因此退出条件为:“所有骰子均为6”
while (array[0] !=6 && array[1] != 6 && array[2] != 6);
这是行不通的,因为它的意思是:“虽然三个尝试都不是6”
因此退出条件为:“至少一个骰子为6”
while (array[0]+array[1]+array[2] != 18);
之所以可以正常工作,是因为它意味着:“模具结果总和为18”
因此退出条件为:“所有骰子均为6”(因为这是加总18的唯一方法)
通常:
do{
something....
}while(some condition is true);
如果要使用“ &&”运算符表示
do{
something....
}
while (!(array[0] == 6 && array[1] == 6 && array[2] == 6));
含义
do {
something...
}while(the expression every element in the array is equal to 6 is false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.