万年历 上
万年历的输出
分步骤来实现,本章先实现两个步骤
(1)实现从控制台接收年和月,判断是否是闰年
(2)编程计算输入月份所对应的天数
运行结果
案例设计
- 使用简单if、嵌套if,else和多重if,else来实现
- 注意else和if的配对
万年历 下
运行结果
案例介绍
- 编程计算输入的月份距离1900年1月1日的天数,求出你输入当前月的天数,求出你输入当月之前的总天数
- 编程计算输入月份的第一天是星期X,(公式:星期X = 1 + 天数差%7)
- 格式化输出XX年XX月日历(一行输出7个)
案例设计
- 使用for循环来计算总天数和打印月份的天数。
import java.util.Scanner;
public class MyCalendar{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("请输入年:");
int year=input.nextInt();
System.out.println("请输入月:");
int month=input.nextInt();
System.out.println("**************** 欢迎使用万年历(*^_^*) ****************");
int days=0;
boolean flag;
System.out.println("您输入的年月为"+year+"年"+month+"月。");
int totalDays=0;
int yearDays;
//----------------------------------------------------------------------------------
// 求出你当年之前的天数
for(int j=1900;j<=year;j++){
// 判断j是否为闰年
if ((j%400==0) || (j%4==0 && j%100!=0)) {
yearDays=366;flag=true;
}else{
yearDays=365;flag=false;
}
if(j<year) {totalDays+=yearDays;} // 计算1900~year-1的总天数
else{ // j==year; 计算1900~year年month月的总天数
// 打印平年还是闰年
if (flag){
System.out.println(year+"年为闰年");
}else{
System.out.println(year+"年非闰年");
}
if (month==1){;}
else{ //从month==2开始,计算1~month月的日期
for(int k=1;k<=month;k++){
switch (k){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days=31;break;
case 2:
if (flag){days=29;}
else{days=28;}break;
case 4:
case 6:
case 9:
case 11:
days=30;break;
default:
System.out.println("你输入的月份有误!");
}
if (k<month) {totalDays+=days;}
else{ //k==month
int currentMonthDays=days;
System.out.println(month+"月份的天数为"+currentMonthDays);
}
}
}
System.out.println("您输入"+year+"年"+month+"月之前的总天数为"+totalDays);
}
}
//----------------------------------------------------------------------------------
System.out.println();
System.out.println(year+"年"+month+"月 日历表");
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
int weekDays=1+totalDays%7; // year年month月是星期weekDays
if (weekDays==7){weekDays=0;} // weekDays==1→星期一;weekDays==0→星期日;
int n=weekDays;
System.out.print("星期"+n);
for(int a=1; a<=weekDays; a++){
System.out.print("\t"); //若weekDays==0,则n=0;若weekDays=3,则n=3
}
for(int b=1; b <= days; b++){
n++;
System.out.print(b+"\t");
if (n%7==0){
System.out.println("\n");
}
}
}
}