需求:
- 输出界面上要求能以一定的格式化形式展示出来,有年、月、星期的信息和字样
- 要求针对不同的子功能设计函数完成,函数数量不得少于3个
- 要求能循环执行,直到用户输入q"时退出
实现:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class RiLi {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("---查询日历选项---");
System.out.println("1.查询一年日历:例如2021");
System.out.println("2.查询单月日历:例如2021 06");
System.out.println("3.退出输入q");
System.out.println("输入选项:");
String choice = sc.nextLine();
switch (choice) {
case "1":
System.out.println("-查询一年日历-");
System.out.println("输入查询年份:");
String year = sc.nextLine();
myyear(year);
break;
case "2":
System.out.println("-查询单月日历-");
System.out.println("输入查询年份:");
String year_solo = sc.nextLine();
System.out.println("输入查询月份:");
String month_solo = sc.nextLine();
myyear(year_solo,month_solo);
break;
case "q":
System.out.println("-退出程序-");
System.exit(0);
}
}
}
// 查询一年的日历
public static void myyear(String year) throws ParseException {
for (int mouth = 1; mouth <=12 ; mouth++) {
System.out.println(mouth + "月 日历:");
int firstDay = 0;
int endDay = 0;
String str = year + "-" + mouth;
DateFormat format = new SimpleDateFormat("yyyy-MM");
Date date = format.parse(str);
Calendar c = new GregorianCalendar();
c.setTime(date);
endDay = c.getActualMaximum(Calendar.DATE);
c.set(Calendar.DATE, 1);
firstDay = c.get(Calendar.DAY_OF_WEEK);
System.out.println("------------------------------------------------------");
System.out.println("周日 周一 周二 周三 周四 周五 周六");
System.out.println("------------------------------------------------------");
for (int j = 1; j < firstDay; j++)
{
System.out.print("\t");
}
for (int i = 1; i <= endDay; i++)
{
System.out.print(i + "\t");
if ((i - (8 - firstDay)) % 7 == 0)
{
System.out.println("\n");
}
}
System.out.println();
}
}
// 查询单月日历
public static void myyear(String year, String month) throws ParseException {
System.out.println(year+"年-"+month+"月 日历:");
int firstDay = 0;
int endDay = 0;
String str = year + "-" + month;
DateFormat format = new SimpleDateFormat("yyyy-MM");
Date date = format.parse(str);
Calendar c = new GregorianCalendar();
c.setTime(date);
endDay = c.getActualMaximum(Calendar.DATE);
c.set(Calendar.DATE, 1);
firstDay = c.get(Calendar.DAY_OF_WEEK);
System.out.println("------------------------------------------------------");
System.out.println("周日 周一 周二 周三 周四 周五 周六");
System.out.println("------------------------------------------------------");
for (int j = 1; j < firstDay; j++)
{
System.out.print("\t");
}
for (int i = 1; i <= endDay; i++)
{
System.out.print(i + "\t");
if ((i - (8 - firstDay)) % 7 == 0)
{
System.out.println("\n");
}
}
}
}