简体   繁体   English

while循环中的多个条件

[英]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);
        }
    }
}

Im trying to iterate through the while loop by adding on a day at a time but it wont even access the while loop the first time. 我试图通过一次添加一天来遍历while循环,但它甚至第一次都不会访问while循环。 Are the conditions in the while loop right? while循环中的条件正确吗? When i tested it it worked with just one condition but stopped when i added the second condition. 当我测试它时,它仅在一种情况下起作用,但是在我添加第二种条件时停止了。

它应该是

while( !(cal.get(Calendar.YEAR) == 2001 && cal.get(Calendar.MONTH) == 0 && cal.get(Calendar.DAY_OF_MONTH) == 1) ) { // while not 1/1/2001

This is just a simple logic error. 这只是一个简单的逻辑错误。 If even one of those is false (say, if the month IS 0), then you have true && false && true, which is false. 如果甚至其中之一为假(例如,如果月份为0),那么您具有true && false && true,这是错误的。

You need the "not" outside of the entire expression, or you need to use "||" 您需要在整个表达式之外添加“ not”,或者您需要使用“ ||” to combine them: 结合起来:

while( !(year == 2001 && month == 0 && day == 1) )

or 要么

while( (year != 2011) || (month != 0) || (day != 1) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM