[英]Logic - Java programming do-while loops
因此,當您使用Java進行編碼並執行do-while循環時,如果有多個條件要破壞循環,則必須使用&&(and)而不是||。 (要么)。 我知道&&將打破循環。
在此示例中,輸入1、2、3或4會中斷循環,但是為什么&&!??! 我的教授無法解釋。
import java.util.*;
public class ErrorTrap
{
public static void main(String[] args)
{
System.out.println("Program by --");
System.out.println();
System.out.println("Error Traps");
System.out.println();
//initialize variables
Scanner input = new Scanner(System.in);
char year;
//user input
do {
System.out.print("Please input a 1, 2, 3 or 4: ");
year = input.nextLine().charAt(0);
//output
System.out.println(num);
System.out.println();
}
while(year != '1' && year != '2' && year != '3' && year != '4');
}//end main
}//end ErrorTrap
假設用戶輸入5
讓我們檢查結果:
5 != 1 is true
5 != 2 is true
5 != 3 is true
5 != 4 is true
true && true && true && true
為true
因此循環不斷循環。
例如,一旦用戶輸入3
,我們將具有以下內容:
3 != 1 is true
3 != 2 is true
3 != 3 is false
3 != 4 is true
true && true && false && true
是false
因此我們打破了循環。
現在假設您考慮使用||
並放入3
:
3 != 1 is true
3 != 2 is true
3 != 3 is false
3 != 4 is true
true || anything
true || anything
給出了true
,是因為你想進入的時候折斷代碼不尊重你的規格2
, 3
或4
小規矩:
如果您使用||
並且第一個測試為true
,編譯器甚至不打擾其余測試,輸出為true
。
&&
相同,第一個測試為false
。
只要年份不等於'1'和'2'和'3'和'4',只要在年份中不執行任何操作,您在do括號中的代碼就會執行。 但是,如果您使用||
而不是&&
,代碼將一直執行。 因為一個條件足夠year!='1',即使year ='2'也會執行代碼。
&& is restricted, you should meet all conditions to validate code.
|| is not restricted, you just need to meet one condition of desired
conditions to validate code.
while(year!='1' && year!='2')
是多個條件的正確語法,因為添加的“ &&”允許程序知道每個條件都依賴於語句中的其他條件,如果一個條件為false,則該語句將中斷。 -而“ ||” 用於獨立語句。
例如,
String Apple = "Red";
if(Apple.equals("Red")||Apple.equals("Green")){
return true;
} else {
return false;
}
即使蘋果不是綠色的,if語句也將返回true,它會檢查是否有一個條件為true。
而
String Apple = "Red";
if(Apple.equals("Red")&&Apple.equals("Green")){
return true;
} else {
return false;
}
無論如何,這都會返回false,因為這兩個條件相互依賴。
希望這對您有所幫助!
while(year!='1'&& year!='2'&& year!='3'&& year!='4');
您將在此處使用&&
運算符,因為要在此處中斷循環,“ year”不能為1,並且不能為2,並且不能為3,也不能為4。
如果要使用OR運算符( ||
),則其中一個可能為false,另一個可能為true,但是循環仍將繼續。
基本上,為了打破循環,您需要year == 1,2,3和4為假。 如果使用&&
,則所有這些都必須為false。 如果使用||
,並非所有循環都必須為假。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.