Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Calendar.getInstance();

 
Dustin Schreader
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Dustin Schreader
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very cool, It works now and I only had to change weekday - 1! Thank you!
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic