已知2017年第一天是星期日 ,打印2017年某月的月历。
输入
输入月份
输出
输出提示:
System.out.printf("%4s%4s%4s%4s%4s%4s%4s","日","一","二","三","四","五","六");
System.out.println("*****"+year+"年"+month+"月份*****");
System.out.printf("%3d",day);
难度
入门
输入示例
5
输出示例
*****2017年5月份*****
日 一 二 三 四 五 六
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
主要时利用循环,但要注意每一个日期的空格和换行;
代码演示:
import java.util.Scanner;
public class Calander {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int i=in.nextInt();
print(i);
}
public static int fun(int i)//确定每个月的天数
{
int k=-1;
switch(i)
{
case 1:case 3: case 5: case 7: case 8: case 10: case 12:k=31;break;
case 4:case 6:case 9: case 11:k=30;break;
case 2:k=28;break;
default:break;
}
return k;
}
public static void print(int i)
{
int sum=0;
int k=fun(i);
for(int j=1;j<i;j++)//2017年第一天是星期一,所以求出总天数,对7取余,可得这个月的第一天时星期几
sum+=fun(j);
int s=sum%7;
System.out.printf("*****2017年%d月份*****\n",i);
System.out.printf("%4s%4s%4s%4s%4s%4s%4s\n","日","一","二","三","四","五","六");
int n=1;//这个月的一号
for(int h=0;h<s;h++)//这个月第一天之前全部输出空格
System.out.printf("%3s"," ");
for(;s<7;s++) //日历的第一行输出完
{
System.out.printf("%3d",n);
n++;
}
System.out.println();//换行
for(int l=0;l<4;l++)//还有四行
{
for(int t=0;t<7;t++)
{
System.out.printf("%3d",n);
n++;
if(n>k)
break;
}
System.out.println();
}
}}