I wrote few lines of code which doesn't work correctly. Why? Could sb explain me?
Calendar date = Calendar.getInstance();
date.set(2010, 03, 7);
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
System.out.println("OK");
I wrote few lines of code which doesn't work correctly. Why? Could sb explain me?
Calendar date = Calendar.getInstance();
date.set(2010, 03, 7);
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
System.out.println("OK");
Because April 7th, 2010 isn't a Sunday. Months start with zero: 0 = January, 1 = February, 2 = March, ...
(Also, side note, you've used octal when specifying the month [03
instead of 3
]. No biggie until you get to September, whereupon 08
is an invalid octal number.)
Months count from zero:
date.set(2010, 2, 7);
Also don't get in the habit of writing numbers with leading zeros. That tells Java (and many other languages) that you want the number interpreted as an octal (base 8) constant, not decimal.
Probably because the month is 0-based, so you set April, 7th, which is a Wednesday.
The month value is 0-based. Java docs for set method of Calendar class
.
Also if you want to check if today(the day the program is run :) ) is Sunday, you need not set anything, because the getInstance
method returns a Calendar object based on the current time in the default time zone with the default locale:
Calendar date = Calendar.getInstance();
//date.set(2010, 03, 7);
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
System.out.println("OK");
To avoid making mistakes, you can use Calendar static values for the month, e.g. :
date.set(2010, Calendar.MARCH, 7);
Is this for Euler 19?
If so, here is a tip, loop from 1901 to 2000, from months 0 to 11, from days 1-31, then ask:
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && day==1)
counter++;