my dog learned polymorphism
The moose likes Beginning Java and the fly likes Using Calendar.getInstance(); Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using Calendar.getInstance();" Watch "Using Calendar.getInstance();" New topic

Using Calendar.getInstance();

Dustin Schreader
Ranch Hand

Joined: May 25, 2009
Posts: 74
I have this method that is supposed to display the day of week given the preferred month, day, and year. When I test this method I get the wrong day and if I try to enter a higher number for the day such as 17 I get an arrayIndexOutofBoundsException: 7. I'm using the gregorianCalendar. Am I not correctly using DAY_OF_WEEK?

Matthew Brown

Joined: Apr 06, 2010
Posts: 4542

The method looks right. But that suggests that the day-of-week is 1-7. But you then use it as an array index, which needs to be 0-6.
bhanu chowdary
Ranch Hand

Joined: Mar 09, 2010
Posts: 256
use getFirstDayOfWeek() and see what is the first day of the week. If this is not the first day according to your week then you can set it. And regarding the Exception you are maintaining an array so the indexes will be from 0 to 6, so use wkDay[weekday-1]. Constant field values for days
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15080

calendar.get(Calendar.DAY_OF_WEEK) returns a number between 1 and 7, where 1 is Sunday, 2 is Monday, etc., until 7 is Saturday.

If you use that number to index into an array, you probably have to subtract 1 from it:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Dustin Schreader
Ranch Hand

Joined: May 25, 2009
Posts: 74
Very cool, It works now and I only had to change weekday - 1! Thank you!
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

Actually, you should subtract Calendar.SUNDAY, as that's the offset. Calendar.SUNDAY just happens to be 1, but if you use this same technique for months (with Calendar.JANUARY being 0, go figure...) you won't end up in any problems.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Using Calendar.getInstance();
It's not a secret anymore!