java万年历
接触java以来第一次使用面向对象的方式进行编程,有点简易,希望大家能多多给一些建议吧
本次练习针对面向对象的方式,分为三个类
方法类
.
用户类``测试类
.
首先是最重要的方法类
public class Date {
//判断闰年
public boolean isRunyear(int year1){
boolean flag = false;
if((year1 % 4 == 0 && year1 % 100 != 0) || (year1 % 400 == 0))
flag = true;
return flag;
}
//计算指定月的天数
public int monthDay(int year, int month)
{
int day1 =30;
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:day1 = 31;break;
case 2: day1 = isRunyear(year)?29:28;break;
}
return day1;
}
//计算指定年的天数
public int yeardays(int year1)
{
return isRunyear(year1)?366:365;
}
//计算年的总天数
public long yearTotalDay(int startYear, int endYear)
{
long days = 0;
for(int year1 = startYear; year1 < endYear; year1++){
days += yeardays(year1);
}
return days;
}
//计算月的天数
public long monthTotalDay(int year, int startMonth, int endMonth)
{
long days = 0;
int day1 = 0;
for(int month1 = startMonth; month1 < endMonth; month1++){
day1 = monthDay(year,month1);
days+=day1;
}
return days;
}
//计算星期
public long curWeek(int oldWeek,long total)
{
long week = (oldWeek+total)%7;
return week;
}
//打印日历
public void printMonth(long week, long curMonthDay)
{
System.out.println("星期天\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for(int i = 0; i < week; i++)
System.out.print("\t\t");
for(int i = 1;i <= curMonthDay;i++){
System.out.print("\t" + i + "\t");
if((week + i) % 7 == 0)
System.out.println();
}
}
}
接下来是用户类
import java.util.Scanner;
public class User {
Scanner sc = new Scanner(System.in);
public int userYear() {
System.out.print("请输入年:");
int year = sc.nextInt();
return year;
}
public int userMonth() {
System.out.print("月份:");
int month = 0;
month = sc.nextInt();
return month;
}
}
最后是测试类:
public class Test {
public static void main(String[] args) {
Date Date = new Date();
User User = new User();
int month = User.userMonth();
int year = User.userYear();
//给定起始年份1900年1月1日为星期一进行判段
long daysTotal = 0;
daysTotal = Date.yearTotalDay(1900, year);
daysTotal += Date.monthTotalDay(year, 1, month);
long week = Date.curWeek(1,daysTotal);
long days1 = Date.monthDay(year, month);
Date.printMonth(week, days1);
}
}
运行结果如下: