Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.8. Code exercise 8

5.8.8. Code exercise 8
Last updated: 27 January 2013.

Write a method named getDayOfWeek(int year, int month, int dayOfMonth) that returns the day of the week for the date represented by the given arguments. For example, since January 1st, 2000 was a Saturday, the call getDayOfWeek(2000, 1, 1) returns Saturday.


import java.util.Calendar;
import java.util.GregorianCalendar;

public final class Practice {

   
private String dayOfWeekToString(int dayOfWeek){
         
switch(dayOfWeek){
         
case Calendar.MONDAY : return "Monday";
         
case Calendar.TUESDAY : return "Tuesday";
         
case Calendar.WEDNESDAY : return "Wednesday";
         
case Calendar.THURSDAY : return "Thursday";
         
case Calendar.FRIDAY : return "Friday";
         
case Calendar.SATURDAY : return "Saturday";
         
case Calendar.SUNDAY : return "Sunday";
         
default : return null;
         
}
    }


   
public String getDayOfWeek(int year, int month, int dayOfMonth){

         
if(year <= 0 || month <= 0 || dayOfMonth <= 0)
               
return null;

          GregorianCalendar calendar =
new GregorianCalendar(year, month-1, dayOfMonth);
         
// The second argument is (month-1) because January is 0, February is 1, ...

         
return dayOfWeekToString(calendar.get(Calendar.DAY_OF_WEEK));
   
}

}


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.8. Code exercise 8
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.9. Code exercise 9

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7