Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*; // for GregorianCalendar
- import javax.swing.*; // required for input dialogs
- public class DayFinder {
- public static void main(String[] args) {
- /**
- * Program : DayFinder.java
- * Purpose : Displays the correct day of week for today's date,
- * and for a date you select (in the past or future)
- * Creator : Chris Clarke
- * Created : 06.01.2011
- */
- // create instance of calendar
- GregorianCalendar now = new GregorianCalendar();
- String message = "Today is ";
- int day = now.get(Calendar.DAY_OF_MONTH);
- int month = now.get(Calendar.MONTH);
- int year = now.get(Calendar.YEAR);
- int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);
- displayWeekDay(message, day, month, year, dayOfWeek);
- String Day;
- Day = JOptionPane.showInputDialog("Enter a date: day of month (1-31)");
- String Month;
- Month = JOptionPane.showInputDialog("Enter a date: month (1-12)");
- String Year;
- Year = JOptionPane.showInputDialog("Enter a date: year (4 digits)");
- // convert Strings to integers
- try {
- day = Integer.parseInt(Day);
- }
- catch (Exception e) {
- System.out.print("Error in day input!");
- System.exit(0);
- }
- try {
- month = Integer.parseInt(Month);
- }
- catch (Exception e) {
- System.out.print("Error in month input!");
- System.exit(0);
- }
- month--;
- try {
- year = Integer.parseInt(Year);
- }
- catch (Exception e) {
- System.out.print("Error in year input!");
- System.exit(0);
- }
- // check that they're within acceptable range
- if (day<1 || day>31) {
- System.out.print("Error in day input! Number outside range");
- System.exit(0);
- }
- if (month<0 || month>11) {
- System.out.print("Error in month input! Number outside range");
- System.exit(0);
- }
- if (year<0 || year>3000) {
- System.out.print("Error in year input! Number outside range");
- System.exit(0);
- }
- GregorianCalendar d = new GregorianCalendar();
- d.set(year, month, day);
- message = "The day in question ";
- if (d.after(now))
- message += "will be a ";
- else
- message += "was a ";
- dayOfWeek = d.get(Calendar.DAY_OF_WEEK);
- displayWeekDay(message, day, month, year, dayOfWeek);
- // end of main program
- }//end main
- public static void displayWeekDay(String message, int day, int month, int year, int dayOfWeek) {
- String weekDay = "";
- switch (dayOfWeek) {
- case 1: weekDay="Sunday"; break;
- case 2: weekDay="Monday"; break;
- case 3: weekDay="Tuesday"; break;
- case 4: weekDay="Wednesday"; break;
- case 5: weekDay="Thursday"; break;
- case 6: weekDay="Friday"; break;
- case 7: weekDay="Saturday"; break;
- default : weekDay="Error";
- }
- // end of switch statement
- System.out.print(message+weekDay);
- System.out.println(" ("+day+"/"+(month+1)+"/"+year+")");
- }//end displayWeekDay
- }//end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement