0
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. Are the conditions in the while loop right? When i tested it it worked with just one condition but stopped when i added the second condition.

2 Answers 2

5

It should be

while( !(cal.get(Calendar.YEAR) == 2001 && cal.get(Calendar.MONTH) == 0 && cal.get(Calendar.DAY_OF_MONTH) == 1) ) { // while not 1/1/2001
Sign up to request clarification or add additional context in comments.

Comments

3

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.

You need the "not" outside of the entire expression, or you need to use "||" to combine them:

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

or

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

2 Comments

+1 because you actually explain the logical error in the opening post.
For those that are interested, the relationship between the two statements here is an application of De Morgan's law: en.wikipedia.org/wiki/De_Morgan's_laws

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.