?
Solved

Code help...

Posted on 2011-10-06
13
Medium Priority
?
201 Views
Last Modified: 2012-06-21
PrintCalendar class below is supposed to print a monthly calendar with the following options:

> java PrintCalendar 5 2010    <-- is supposed to print month= 5 and year = 2010

> java PrintCalendar 5            <-- is supposed to print month= 5 and year = current year

> java PrintCalendar              <-- no arguments is supposed to print month= current month
                                                  and year = current year

This part is working but the rest printMonth(yy, mm); in main() is not working.

Question: Could you locate the problem here?

Having:

static int mm;
static int yy;

on the top doesn't help very much either.

Thank you.
import java.text.SimpleDateFormat;

public class PrintCalendar {

    static SimpleDateFormat sdfy = new SimpleDateFormat("yyyy");
    static SimpleDateFormat sdfm = new SimpleDateFormat("MM");
static int mm;
static int yy;

   public static String getDateString(String [] ss) throws WrongNumberOfInputsException {

       String month = "";
        String year = "";
       java.util.Date dd = new java.util.Date();



          if(ss.length > 2)throw new   WrongNumberOfInputsException (" too many arguments");
         else  if(ss.length == 2){
              int m = -1;
              int y = -1;
              try {
                m = Integer.parseInt(ss[0]);
                y = Integer.parseInt(ss[1]);
             }  catch(Exception ex){

              }
            if( m < 1 || m > 12 || y < 1900 || y > 2100)throw  new   WrongNumberOfInputsException (" wrong year or month");
              year = ss[1];
              month = ss[0];
              while(month.length() < 2)month = "0" + month;

          }   else if (ss.length == 1){
              int m = -1;
               try {
                m = Integer.parseInt(ss[0]);

             }  catch(Exception ex){

              }
               if( m<1 || m >12)throw  new   WrongNumberOfInputsException (" wrong year or month");

              month = ss[0];
                while(month.length() < 2)month = "0" + month;
              year = sdfy.format(dd);
          }  else if (ss.length == 0){
              month = sdfm.format(dd);
              year = sdfy.format(dd);

          }

        return (month + "-" + year);
   }

    public static void main(String[] args) {
                String dateString = "";
  int m=0;
  int y=0;

           try{
               dateString = getDateString(args);
//               printMonth(year, month);
               String mmmm=(dateString).substring(1,2);
               mm=Integer.parseInt(mmmm);
               String yyyy=(dateString).substring(2,6);
               yy=Integer.parseInt(yyyy);
               
           }  catch(Exception ex){
               System.out.println(ex);
               System.out.println("usage");
               System.exit(0);

           }

        printMonth(yy, mm);
    }

/** Print the calendar for a Month in a year */
public static void printMonth(int year, int month) {
    // Print the headings of the calendar
    printMonthTitle(yy, mm);
    
    // Print the body of the calendar
    printMonthBody(yy, mm);
}

/** Print A stub for printMonthTitle may look like this */
public static void printMonthTitle(int year, int month) {
    System.out.println("       " + getMonthName(month)
            + " " + year);
    System.out.println("_____________________________");
    System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}

/** Get the English name for month */
public static String getMonthName(int month) {
    String monthName = " ";
    switch(month) {
        case 1: monthName = "January"; break;
        case 2: monthName = "February"; break;
        case 3: monthName = "March"; break;
        case 4: monthName = "April"; break;
        case 5: monthName = "May"; break;
        case 6: monthName = "June"; break;
        case 7: monthName = "July"; break;
        case 8: monthName = "August"; break;
        case 9: monthName = "September"; break;
        case 10: monthName = "October"; break;
        case 11: monthName = "November"; break;
        case 12: monthName = "December";    
    }
    
    return monthName;
}

/** Print month body */
public static void printMonthBody(int year, int month) {
    // Get start day of the week for the first date in the month
    int startDay = getStartDay(year, month);
    
    // Get number of days in month 
    int numberOfDaysInMonth =getNumberOfDaysInMonth(year, month);
    
    // Pad space before the first day of the month
    int i = 0;
    for (i = 0; i < startDay; i++)
        System.out.print("    ");
    
    for (i = 1; i <= numberOfDaysInMonth; i++) {
        System.out.printf("%4d", i);
        
        if ((i + startDay) % 7 == 0)
         System.out.println();   
    }
  
  System.out.println();  
}

/** Get the start day of month/1/year */
public static int getStartDay(int year, int month) {
    final int START_DAY_FOR_JAN_1_1800 = 3;
    // get total number of days from 1/1/1800 to month/1/year
    int totalNumberOfDays = getTotalNumberOfDays(year, month);
    
    // Returnthe start day for month/1/year
    return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
}

/** A stub for getTotalNumberOfDays may look like this */
public static int getTotalNumberOfDays(int year, int month) {
    int total = 0;
    
    // Get the total days from 1800 to 1/1/year
    for (int i = 1800; i < year; i++)
        if(isLeapYear(i))
            total = total + 366;
    else
            total = total + 365;
    
    // Add days from Jan to the month prior to the calandar month
    for (int i = 1; i < month; i++)
        total = total + getNumberOfDaysInMonth(year, i);
    
    return total;

}
/** Get the number of days in a mMonth */
public static int getNumberOfDaysInMonth(int year, int month) {
    if ((month == 1) || (month == 3) || (month == 5) || (month == 7) || 
     (month == 8) || (month == 10) || (month == 12))
     return 31;

    if (month == 4 || month == 6 || month == 9 || month == 11)
        return 30;
    
    if (month == 2) return isLeapYear(year) ? 29 : 28;
    
    return 0; // if month is incorrect
}

/** Determine if the year is leap */
public static boolean isLeapYear(int year) {
    return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
}
}

Open in new window

0
Comment
Question by:Mike Eghtebas
  • 8
  • 5
13 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36928366

prints for me only prints 201 instead of 2010 in the heeader - otherwise prints - i didn't change anything

       March -201
_____________________________
 Sun Mon Tue Wed Thu Fri Sat
                           1
   2   3   4   5   6   7   8
   9  10  11  12  13  14  15
  16  17  18  19  20  21  22
  23  24  25  26  27  28  29
  30  31

Open in new window

0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36928385
String yyyy=(dateString).substring(2,6);

should be

String yyyy=(dateString).substring(2,7);
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36928386
OK. That's fine.
So that was the issue?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36928387
sorry

String yyyy=(dateString).substring(3,7);   see line 24

this code is not working when mont has two digits
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36928397
Alos, when it prints 10 2011 for example, the starting day turns out to be Thursday where Sunday is correct. It is off by couple of days.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36928421
>starting day turns out to be Thursday where Sunday is correct

Sunday is incorrect, Saturday is correct

import java.text.SimpleDateFormat;

public class PrintCalendar {

    static SimpleDateFormat sdfy = new SimpleDateFormat("yyyy");
    static SimpleDateFormat sdfm = new SimpleDateFormat("MM");
static int mm;
static int yy;

   public static String getDateString(String [] ss) throws WrongNumberOfInputsException {

       String month = "";
        String year = "";
       java.util.Date dd = new java.util.Date();



          if(ss.length > 2)throw new   WrongNumberOfInputsException (" too many arguments");
         else  if(ss.length == 2){
              int m = -1;
              int y = -1;
              try {
                m = Integer.parseInt(ss[0]);
                y = Integer.parseInt(ss[1]);
             }  catch(Exception ex){

              }
            if( m < 1 || m > 12 || y < 1900 || y > 2100)throw  new   WrongNumberOfInputsException (" wrong year or month");
              year = ss[1];
              month = ss[0];
              while(month.length() < 2)month = "0" + month;

          }   else if (ss.length == 1){
              int m = -1;
               try {
                m = Integer.parseInt(ss[0]);

             }  catch(Exception ex){

              }
               if( m<1 || m >12)throw  new   WrongNumberOfInputsException (" wrong year or month");

              month = ss[0];
                while(month.length() < 2)month = "0" + month;
              year = sdfy.format(dd);
          }  else if (ss.length == 0){
              month = sdfm.format(dd);
              year = sdfy.format(dd);

          }

        return (month + "-" + year);
   }

    public static void main(String[] args) {
                String dateString = "";
  int m=0;
  int y=0;

           try{
               dateString = getDateString(args);
//               printMonth(year, month);
               String mmmm=(dateString).substring(0,2);
               mm=Integer.parseInt(mmmm);
               String yyyy=(dateString).substring(3,7);
               yy=Integer.parseInt(yyyy);

           }  catch(Exception ex){
               System.out.println(ex);
               System.out.println("usage");
               System.exit(0);

           }

        printMonth(yy, mm);
    }

/** Print the calendar for a Month in a year */
public static void printMonth(int year, int month) {
    // Print the headings of the calendar
    printMonthTitle(yy, mm);

    // Print the body of the calendar
    printMonthBody(yy, mm);
}

/** Print A stub for printMonthTitle may look like this */
public static void printMonthTitle(int year, int month) {
    System.out.println("       " + getMonthName(month)
            + " " + year);
    System.out.println("_____________________________");
    System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}

/** Get the English name for month */
public static String getMonthName(int month) {
    String monthName = " ";
    switch(month) {
        case 1: monthName = "January"; break;
        case 2: monthName = "February"; break;
        case 3: monthName = "March"; break;
        case 4: monthName = "April"; break;
        case 5: monthName = "May"; break;
        case 6: monthName = "June"; break;
        case 7: monthName = "July"; break;
        case 8: monthName = "August"; break;
        case 9: monthName = "September"; break;
        case 10: monthName = "October"; break;
        case 11: monthName = "November"; break;
        case 12: monthName = "December";
    }

    return monthName;
}

/** Print month body */
public static void printMonthBody(int year, int month) {
    // Get start day of the week for the first date in the month
    int startDay = getStartDay(year, month);

    // Get number of days in month

   // System.out.println("year: " + year + " month " + month);
    int numberOfDaysInMonth =getNumberOfDaysInMonth(year, month);

  //  System.out.println("numb days: " + numberOfDaysInMonth );

    // Pad space before the first day of the month
    int i = 0;
    for (i = 0; i < startDay; i++)
        System.out.print("    ");

    for (i = 1; i <= numberOfDaysInMonth; i++) {
        System.out.printf("%4d", i);

        if ((i + startDay) % 7 == 0)
         System.out.println();
    }

  System.out.println();
}

/** Get the start day of month/1/year */
public static int getStartDay(int year, int month) {
    final int START_DAY_FOR_JAN_1_1800 = 3;
    // get total number of days from 1/1/1800 to month/1/year
    int totalNumberOfDays = getTotalNumberOfDays(year, month);

    // Returnthe start day for month/1/year
    return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
}

/** A stub for getTotalNumberOfDays may look like this */
public static int getTotalNumberOfDays(int year, int month) {
    int total = 0;

    // Get the total days from 1800 to 1/1/year
    for (int i = 1800; i < year; i++)
        if(isLeapYear(i))
            total = total + 366;
    else
            total = total + 365;

    // Add days from Jan to the month prior to the calandar month
    for (int i = 1; i < month; i++)
        total = total + getNumberOfDaysInMonth(year, i);

    return total;

}
/** Get the number of days in a mMonth */
public static int getNumberOfDaysInMonth(int year, int month) {
    if ((month == 1) || (month == 3) || (month == 5) || (month == 7) ||
     (month == 8) || (month == 10) || (month == 12))
     return 31;

    if (month == 4 || month == 6 || month == 9 || month == 11)
        return 30;

    if (month == 2) return isLeapYear(year) ? 29 : 28;

    return 0; // if month is incorrect
}

/** Determine if the year is leap */
public static boolean isLeapYear(int year) {
    return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
}
}

Open in new window



      October 2011
_____________________________
 Sun Mon Tue Wed Thu Fri Sat
                           1
   2   3   4   5   6   7   8
   9  10  11  12  13  14  15
  16  17  18  19  20  21  22
  23  24  25  26  27  28  29
  30  31

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36928430

String dateString = "03-2010";

String month = dateString.substring(0,2);  ("03")


String year = dateString.substring(3,7);  ("2010")  (can also do just dateString.substring(3);   );



0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36928524
in line 30, you concatinate mont and year like:

return (month + "-" + year);

Then I stored them in static variables mm and yy at lines 64, and 66.

using:

               String mmmm=(dateString).substring(0,2);
               mm=Integer.parseInt(mmmm);
               String yyyy=(dateString).substring(3,7);
               yy=Integer.parseInt(yyyy);

This will work only when month is single digit and it will fail for oct, nov, and December.

I am sure this could be done in a more elegant way and also could include these three months.

Could you possibly give me a way forward on this part. This way, I no longer need to have static int mm; and static int yy; at the very top.

Yes, Saturday is correct for Oct 2011.

Thanks,

Mike



0
 
LVL 47

Expert Comment

by:for_yan
ID: 36928531
dodn't know what you are saying about static, but I jsut showed you for october it is working
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36928548
I changed all static to non-static -and there ist is for November 2011:

import java.text.SimpleDateFormat;

public class PrintCalendar {

    static SimpleDateFormat sdfy = new SimpleDateFormat("yyyy");
    static SimpleDateFormat sdfm = new SimpleDateFormat("MM");
//static int mm;
//static int yy;

   public static String getDateString(String [] ss) throws WrongNumberOfInputsException {

       String month = "";
        String year = "";
       java.util.Date dd = new java.util.Date();



          if(ss.length > 2)throw new   WrongNumberOfInputsException (" too many arguments");
         else  if(ss.length == 2){
              int m = -1;
              int y = -1;
              try {
                m = Integer.parseInt(ss[0]);
                y = Integer.parseInt(ss[1]);
             }  catch(Exception ex){

              }
            if( m < 1 || m > 12 || y < 1900 || y > 2100)throw  new   WrongNumberOfInputsException (" wrong year or month");
              year = ss[1];
              month = ss[0];
              while(month.length() < 2)month = "0" + month;

          }   else if (ss.length == 1){
              int m = -1;
               try {
                m = Integer.parseInt(ss[0]);

             }  catch(Exception ex){

              }
               if( m<1 || m >12)throw  new   WrongNumberOfInputsException (" wrong year or month");

              month = ss[0];
                while(month.length() < 2)month = "0" + month;
              year = sdfy.format(dd);
          }  else if (ss.length == 0){
              month = sdfm.format(dd);
              year = sdfy.format(dd);

          }

        return (month + "-" + year);
   }

    public static void main(String[] args) {
                String dateString = "";
  int m=0;
  int y=0;
        int mm = -1;
        int yy = -1;

           try{
               dateString = getDateString(args);
//               printMonth(year, month);
               String mmmm=(dateString).substring(0,2);
               mm=Integer.parseInt(mmmm);
               String yyyy=(dateString).substring(3,7);
               yy=Integer.parseInt(yyyy);

           }  catch(Exception ex){
               System.out.println(ex);
               System.out.println("usage");
               System.exit(0);

           }

        printMonth(yy, mm);
    }

/** Print the calendar for a Month in a year */
public static void printMonth(int year, int month) {
    // Print the headings of the calendar
    printMonthTitle(year, month);

    // Print the body of the calendar
    printMonthBody(year, month);
}

/** Print A stub for printMonthTitle may look like this */
public static void printMonthTitle(int year, int month) {
    System.out.println("       " + getMonthName(month)
            + " " + year);
    System.out.println("_____________________________");
    System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}

/** Get the English name for month */
public static String getMonthName(int month) {
    String monthName = " ";
    switch(month) {
        case 1: monthName = "January"; break;
        case 2: monthName = "February"; break;
        case 3: monthName = "March"; break;
        case 4: monthName = "April"; break;
        case 5: monthName = "May"; break;
        case 6: monthName = "June"; break;
        case 7: monthName = "July"; break;
        case 8: monthName = "August"; break;
        case 9: monthName = "September"; break;
        case 10: monthName = "October"; break;
        case 11: monthName = "November"; break;
        case 12: monthName = "December";
    }

    return monthName;
}

/** Print month body */
public static void printMonthBody(int year, int month) {
    // Get start day of the week for the first date in the month
    int startDay = getStartDay(year, month);

    // Get number of days in month

   // System.out.println("year: " + year + " month " + month);
    int numberOfDaysInMonth =getNumberOfDaysInMonth(year, month);

  //  System.out.println("numb days: " + numberOfDaysInMonth );

    // Pad space before the first day of the month
    int i = 0;
    for (i = 0; i < startDay; i++)
        System.out.print("    ");

    for (i = 1; i <= numberOfDaysInMonth; i++) {
        System.out.printf("%4d", i);

        if ((i + startDay) % 7 == 0)
         System.out.println();
    }

  System.out.println();
}

/** Get the start day of month/1/year */
public static int getStartDay(int year, int month) {
    final int START_DAY_FOR_JAN_1_1800 = 3;
    // get total number of days from 1/1/1800 to month/1/year
    int totalNumberOfDays = getTotalNumberOfDays(year, month);

    // Returnthe start day for month/1/year
    return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
}

/** A stub for getTotalNumberOfDays may look like this */
public static int getTotalNumberOfDays(int year, int month) {
    int total = 0;

    // Get the total days from 1800 to 1/1/year
    for (int i = 1800; i < year; i++)
        if(isLeapYear(i))
            total = total + 366;
    else
            total = total + 365;

    // Add days from Jan to the month prior to the calandar month
    for (int i = 1; i < month; i++)
        total = total + getNumberOfDaysInMonth(year, i);

    return total;

}
/** Get the number of days in a mMonth */
public static int getNumberOfDaysInMonth(int year, int month) {
    if ((month == 1) || (month == 3) || (month == 5) || (month == 7) ||
     (month == 8) || (month == 10) || (month == 12))
     return 31;

    if (month == 4 || month == 6 || month == 9 || month == 11)
        return 30;

    if (month == 2) return isLeapYear(year) ? 29 : 28;

    return 0; // if month is incorrect
}

/** Determine if the year is leap */
public static boolean isLeapYear(int year) {
    return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
}
}

Open in new window


java PrintCalendar 11 2011
       November 2011
_____________________________
 Sun Mon Tue Wed Thu Fri Sat
           1   2   3   4   5
   6   7   8   9  10  11  12
  13  14  15  16  17  18  19
  20  21  22  23  24  25  26
  27  28  29  30

Open in new window



the same code for March given this way:

java PrintCalendar 3 2011

       March 2011
_____________________________
 Sun Mon Tue Wed Thu Fri Sat
           1   2   3   4   5
   6   7   8   9  10  11  12
  13  14  15  16  17  18  19
  20  21  22  23  24  25  26
  27  28  29  30  31

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36928558
In your code iit was this way
and it was incorrect:

 dateString = getDateString(args);
//               printMonth(year, month);
               String mmmm=(dateString).substring(1,2);
               mm=Integer.parseInt(mmmm);
               String yyyy=(dateString).substring(2,6);
               yy=Integer.parseInt(yyyy);

Open in new window


it should be (0,2) and (3,7)

From the method ilways returns 2-4, like

02-2011 or 10-2011

because I have this statement in the method:
   while(month.length() < 2)month = "0" + month;
so even when user inoputs 3 2011 it will return 03-2011
and therefore

 String mmmm=(dateString).substring(0,2);
        String yyyy=(dateString).substring(3,7);

will  be correct both for 02-2011 and for 11-2011




0
 
LVL 34

Author Closing Comment

by:Mike Eghtebas
ID: 36928576
Thank you.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36928812
You are always welcome.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month15 days, 4 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question