简体   繁体   中英

Make a calendar starting on a specified day of the week

Ok, so I am trying to make a calendar that allows the user to input both the day that the first Monday is of the month and the total number of days in the month.

The output should look something like this: (See linked image)

IMAGE

This is what I have so far:

int daysLeft = numDays;

for(int week = 1; week <= 5; week++)
     {
        if(daysLeft > 1)
        {
           for(int day = 1; day <= numDays; day++)
           {
              if((day % 7) == 1) , if the day % 7 (a week) is equal to 1 then go to the next line
              {
                 System.out.println();
              }

              System.out.print(day); 
              daysLeft--; 
           }
        }
     }

I want to use nested-for loops for this, I know it can be done and I know I could use the calendar class but I am learning and would like to use for loops. So, the above code works if the first Monday is also the fist day.

With all that out of the way, based on the above info, how can I make a way using for loops to change the starting position of the month?

Edit Ignore leap years.

1) You probably don't need a nested for loop, your outer-for loop did nothing actually

2) I am still a bit unclear ab your requirements, this is the best I could come up and I think it does what you described nicely:

public static void printCalendar(int monday, int numDays) {
    if (monday > 7 || monday < 1) throw new IllegalArgumentException("Invalid monday.");
    if (numDays > 31 || numDays < 1 || numDays < monday) throw new IllegalArgumentException("Invalid numDays.");

    System.out.print("Mon\t");
    System.out.print("Tue\t");
    System.out.print("Wed\t");
    System.out.print("Thur\t");
    System.out.print("Fri\t");
    System.out.print("Sat\t");
    System.out.print("Sun\t");
    System.out.println();

    int padding = (7 - (monday - 1)) % 7;

    for (int i = 0; i < padding; i++) {
        System.out.print(" \t");
    }

    for (int day = 1; day <= numDays; day++) {
        if ((padding + day) % 7 == 0)
            System.out.println(day + "\t");
        else
            System.out.print(day + "\t");
    }
}

sample output with printCalendar(3, 31);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM