万年历练习
- 此次练习分为三个类:
-
1、方法类
-
2、用户类
-
3、测试类
首先开始编写Calculator.java的方法类
package com.hellojava.lunar;
public class Calculator {
//判断是否为闰年
public static boolean isLeapYear(int year) {
boolean bool = false;
if((year%4==0 && year%100!=0) || (year%400==0)) {
bool = true;
}
return bool;
}
//判断每个月的天数
public int monthDay(int year,int month) {
int monthday = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
monthday = 31;
break;
case 4:
case 6:
case 9:
case 11:
monthday = 30;
break;
case 2:monthday = isLeapYear(year)?29:28;
}
return monthday;
}
//计算从1900年到当前年的总天数
public int totalYearDay(int year) {
int totalyearday = 0;
for(int i = 1900; i<year; i++) {
if(isLeapYear(i)) {
totalyearday+=366;
}else {
totalyearday+=365;
}
}
return totalyearday;
}
//计算1月到当前月份的总天数
public int totalMonthDay(int year,int month) {
int totalmonthday = 0;
for(int i = 1; i<month; i++) {
totalmonthday+=monthDay(year, i);
}
return totalmonthday;
}
//计算打印从星期几开始
public int calcWeek(int year,int month) {
int totalDay = totalYearDay(year)+totalMonthDay(year, month);
int week = (totalDay+1)%7;
return week;
}
//打印日历
public void printData(int year,int month) {
int start = calcWeek(year, month);
System.out.println("星期天\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for(int i = 0; i<start; i++) {
System.out.print(" "+"\t");
}
int monthdays = monthDay(year, month);
for(int j = 1; j<=monthdays; j++) {
System.out.print(" "+j+"\t");
if((j+start)%7==0) {
System.out.println();
}
}
}
}
第二部编写User.java类
package com.hellojava.lunar;
import java.util.Scanner;
public class User {
Scanner sc =new Scanner(System.in);
//输入年份
public int inputYear() {
System.out.println("请输入年份:");
return sc.nextInt();
}
//输入月份
public int inputMonth() {
System.out.println("请输入月份:");
return sc.nextInt();
}
}
最后编写run.java进行测试
package com.hellojava.lunar;
public class Run {
public static void main(String[] args) {
Calculator calc = new Calculator();
User user = new User();
int year = user.inputYear();
int month = user.inputMonth();
calc.printData(year, month);
}
}
运行结果如下: