找到休息日
需求:
某公司软件开发工程师孙工,作息规律为上三天班,休息一天,经常不确定休
息日是否周末,为此,请你开发一个程序,当孙工输入年及月,以日历方式显示对
应月份的休息日,用中括号进行标记.同时,统计出本月有几天休息,轮到周末休
息有几天.(注:首次休息日是 2020 年 2 月 2 日)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
/**
* @author MJL
* @create 2020-11-15 22:38
*/
public class Text02 {
private static View view = new View();
private static boolean isContinue = true;
public static void main(String[] args) throws ParseException {
view.welcome();
printCalendar();
}
private static void printCalendar() throws ParseException {
while (isContinue){
/**
* 获取年月
*/
int year = view.getYearView();
int month = view.getMonthView()-1;
Calendar calendar = Calendar.getInstance();
//每个月的1号开始算
calendar.set(year,month,1);
//获取当月最大天数
int maximum = calendar.getMaximum(Calendar.DAY_OF_MONTH);
//获得今天星期几
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
//调用星期显示
view.WeekListView();
//第一天前空格
for (int i=1;i<dayOfWeek;i++){
System.out.printf("%-8s","");
}
//本月休息天数, 本月周末休息天数
int relaxDay = 0;
int relaxWeekend = 0;
for (int i=1;i<=maximum;i++){
//设置当前月份
calendar.set(Calendar.DAY_OF_MONTH,i);
//获取当前日期
Date currentDate = calendar.getTime();
//获取当周的日期
int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (isRelax(currentDate)){
System.out.printf("%-8s", "[" + i + "]");
relaxDay++;
if (currentDayOfWeek == 1 || currentDayOfWeek == 7){
relaxWeekend++;
}
}else {
System.out.printf("%-8d", i);
}
if (currentDayOfWeek == 7) {
System.out.println(" ");
}
}
System.out.println(" ");
System.out.println("本月休息天数有" + relaxDay + "天");
System.out.println("本月轮到周末休息天数有" + relaxWeekend + "天");
}
}
/**
* 判断是否为休息日
* @param date
* @return
*/
public static boolean isRelax(Date date) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//假设第一次休假的日期为2020-02-02
Date beginDate = dateFormat.parse("2020-02-01");
long beginTime = beginDate.getTime(); //2020-02-02秒数
long endTime = date.getTime(); //现在的秒数
int day = (int) ((endTime-beginTime)/1000/60/60/24);
//有隔开的天数
if (day >=0 && day%4==1){
return true;
}
return false;
}
}
class View{
Scanner scan = new Scanner(System.in);
/**
* 输入年份
* @return
*/
public int getYearView(){
System.out.println("请输入年:");
int year = scan.nextInt();
return year;
}
/**
* 输入月份
* @return
*/
public int getMonthView(){
System.out.println("请输入月份:");
int month = scan.nextInt();
return month;
}
public void welcome() {
System.out.println("欢迎使用日历标记系统!");
}
public void bye() {
System.out.println("谢谢使用,再见!");
}
public void WeekListView() {
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
}
}