[英]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.