打印任一年日历
知识点:for语句,if语句,switch语句,return语句。
import java.util.Scanner;
public class Switch {
static int year,weekday;
public static boolean isLeapYear(int year){
return((year % 4 == 0 && year % 100 !=0)||(year % 400 ==0));
}//判断是否闰年
public static int firstWeekDayOfYear(int year){//判断每年的第一天是星期几
long day=365*year;
for(int i=1;i<year;i++)
if( isLeapYear(i) )
day +=1;
return (int) day % 7; //注意返回值和该函数的变量
}
public static int getMounthOfDays(int mouth){//获取每个月的天数
switch(mouth){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if(isLeapYear(year))
return 29;
else
return 28;
default:
return 0;
}
}
public static void showMouth(){//逐一打印一年12个月份
for(int m=1;m<=12;m++){
System.out.println(m+"月");
System.out.println("Sunday Monday Tuesday Wednesday Thursday Friday Saturday");
for(int j=1;j<=weekday;j++){
System.out.print(" ");//打印每月第一天前面的空格
}
int mouthDay=getMounthOfDays(m);
for(int d=1;d<=mouthDay;d++){
if(d<10)
System.out.print(" "+"0"+d+" ");
else
System.out.print(" "+d+" ");
weekday= (weekday+1) % 7 ; //判断当天的第二天是星期几
if(weekday == 0)//如果第二天是星期日,就换行
System.out.println();
}
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("请输入一个年份 ");
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
year=Integer.parseInt(str);
weekday=firstWeekDayOfYear(year);
System.out.println("\n "+year+" ");
showMouth();
}
}
打印出来的数字和星期会出现不对齐的情况,是因为输出的空格数不确定。