[英]Multiple conditions in a while loop
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CountingSundays {
public static void main(String args[]) {
Calendar cal = new GregorianCalendar(1901, 00, 01); // month set to 0for jan , 1= feb etc
while((cal.get(Calendar.YEAR) != 2001) && (cal.get(Calendar.MONTH) != 0) && cal.get(Calendar.DAY_OF_MONTH) != 1) { // while not 1/1/2001
System.out.print(cal.get(Calendar.MONTH));
// cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
我試圖通過一次添加一天來遍歷while循環,但它甚至第一次都不會訪問while循環。 while循環中的條件正確嗎? 當我測試它時,它僅在一種情況下起作用,但是在我添加第二種條件時停止了。
它應該是
while( !(cal.get(Calendar.YEAR) == 2001 && cal.get(Calendar.MONTH) == 0 && cal.get(Calendar.DAY_OF_MONTH) == 1) ) { // while not 1/1/2001
這只是一個簡單的邏輯錯誤。 如果甚至其中之一為假(例如,如果月份為0),那么您具有true && false && true,這是錯誤的。
您需要在整個表達式之外添加“ not”,或者您需要使用“ ||” 結合起來:
while( !(year == 2001 && month == 0 && day == 1) )
要么
while( (year != 2011) || (month != 0) || (day != 1) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.