从一周中的指定日期开始制作日历

时间:2016-10-05 04:38:24

标签: java for-loop calendar

好的,所以我正在尝试制作一个日历,允许用户输入第一个星期一的月份和月份的总天数。

输出应该如下所示: (见链接图片)

IMAGE

这是我到目前为止所拥有的:

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--; 
           }
        }
     }

我想为此使用嵌套for循环,我知道它可以完成,我知道我可以使用日历类但我正在学习并且想要使用for循环。所以,上面的代码工作如果第一个星期一也是第一天。

基于以上信息,如果完成所有这些,我如何使用for循环来改变月份的起始位置?

修改 忽略闰年。

1 个答案:

答案 0 :(得分:1)

1)你可能不需要嵌套for循环,你的outer-for循环实际上没有做任何事情

2)我仍然有点不清楚你的要求,这是我能提出的最好的,我认为它做得很好你所描述的:

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);