用Java編程輸出萬年歷的功能實現
1、功能實現
輸入1查看上個月日歷輸入2查看下個月日歷輸入3查看去年本月日歷輸入4查看明年本月日歷輸入5查看指定月份日歷
2、代碼所導入的包
import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Scanner;
3、main函數和定義的屬性
static Scanner key=new Scanner(System.in);//創建鍵盤掃描器public static void main(String[] args) {Calendar cal=new GregorianCalendar();showTime(cal);//顯示本月日歷while(true) {help();//調出幫助菜單int num=key.nextInt();//菜單輸入選項switch(num) {case 1:lastMonth();break;//查找上個月日歷case 2:nextMonth();break;//查找下個月日歷case 3:lastYearMonth();break;//查找去年本月日歷case 4:nextYearMonth();break;//查找明年本月日歷case 5:chooseMonth();break;//查找指定時間日歷default :System.out.println('請輸入正確的指令:');}}}
4、查找去年本月日歷方法
private static void lastYearMonth() {//查找去年本月日歷Calendar cal=new GregorianCalendar();cal.add(Calendar.YEAR,-1);//將時間轉換到去年showTime(cal);//調用showTime()方法,打印日歷}
5、查找明年本月日歷
private static void nextYearMonth() {//查找明年本月日歷Calendar cal=new GregorianCalendar();cal.add(Calendar.YEAR,1);//將時間轉換到明年showTime(cal);//調用showTime()方法,打印日歷}
6、查找指定時間日歷
private static void chooseMonth() {//查找指定時間日歷System.out.println('請輸入時間,如 2020-2');String str=key.next();SimpleDateFormat sdf=new SimpleDateFormat('yyyy-MM');//轉換字符串時間為date類型Date date=null;try {//拋出異常date=sdf.parse(str);} catch (ParseException e) {e.printStackTrace();}Calendar cal= new GregorianCalendar();cal.setTime(date);//將date的時間類型轉換為CalendarshowTime(cal);////調用showTime()方法,打印日歷}
7、查找下個月日歷
private static void nextMonth() {//查找下個月日歷Calendar cal=new GregorianCalendar();cal.add(Calendar.MONTH,1);//將時間轉換到下個月showTime(cal);//調用showTime()方法,打印日歷}
8、查找上個月日歷
private static void lastMonth() {//查找上個月日歷Calendar cal=new GregorianCalendar();cal.add(Calendar.MONTH,-1);//將時間轉換到上個月showTime(cal);//調用showTime()方法,打印日歷}
9、打印幫助目錄
private static void help() {//打印幫助目錄System.out.println('*****************');System.out.println('輸入1查看上個月日歷');System.out.println('輸入2查看下個月日歷');System.out.println('輸入3查看去年本月日歷');System.out.println('輸入4查看明年本月日歷');System.out.println('輸入5查看指定月份日歷');System.out.println('*****************');}
10、該方法用來展示所搜索的時間
private static void showTime(Calendar cal) {//該方法用來展示所搜索的時間int touday=cal.getActualMaximum(Calendar.DATE);//獲取當月的總天數cal.set(Calendar.DATE,1);//將時間設置成一個月的第一天System.out.println('一t二t三t四t五t六t日');//將星期的文字表示出來int weekday=cal.get(Calendar.DAY_OF_WEEK);//獲取每月第一天是星期幾for(int i=1;i<weekday-1;i++) {//輸出首日前面的空格System.out.print('t');}for(int i=1;i<=touday;i++) {//將一月里的每一天輸出System.out.print(i+'t');if((i+weekday-2)%7==0) {//輸出換行,加上前面的空格數再換行System.out.println();}}System.out.println();System.out.println('*****************');}}
代碼運行結果如下:
到此這篇關于用Java編程輸出萬年歷的功能實現的文章就介紹到這了,更多相關Java輸出萬年歷內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: