您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)使用java在對(duì)日歷進(jìn)行打印,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
//引入Scanner類(lèi),用于從控制臺(tái)輸入年月 import java.util.Scanner; //程序開(kāi)始 class Rili{ //主方法,程序執(zhí)行的入口 public static void main(String[] args){ inputYearAndMonth(); } /** *此方法用于從控制臺(tái)輸入年、月 **/ public static void inputYearAndMonth(){ Scanner sc = new Scanner(System.in); System.out.println("請(qǐng)輸入年"); int year = sc.nextInt(); System.out.println("請(qǐng)輸入月"); int month = sc.nextInt(); printRiLi(year , month); } /** * 打印日歷 **/ public static void printRiLi(int year,int month){ //一周七天,定義一個(gè)計(jì)數(shù)器,打印一天加1(包括空白)如果%7等于0的話(huà)就需要換行 int count = 0; System.out.println("\t---下面打印的是:"+year+"年"+month+"月的日歷表---"); System.out.println(); System.out.println("星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t星期日"); for(int i = 1;i <= getSpace(year,month);i++){ System.out.print("\t"); count +=1; } for(int i = 1;i <= getDaysOfMonth(year ,month);i++){ System.out.print(i+"\t"); count +=1; if(count % 7 ==0){ System.out.println(); } } } /** *判斷年份是平年還是閏年(用于判斷一年有365天或366天,并用于判斷2月有28天或29天),返回值是true(29天、366天)和flase(28天、365天) **/ public static boolean isLoopYear(int year){ return (year %4 ==0 && year % 100 !=0) || (year % 400 == 0); } /** * 獲得某月的天數(shù) **/ public static int getDaysOfMonth(int year ,int month){ int days = 0; switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: days = isLoopYear(year)? 29:28; break; } return days; } /** * 獲得自1900年至當(dāng)前年、月經(jīng)過(guò)的總天數(shù) * 實(shí)現(xiàn):1900年到y(tǒng)ear - 1 年的總天數(shù) * 當(dāng)年至month - 1 的總在數(shù) * 兩個(gè)天數(shù)之和相加 **/ public static int getTotalDays(int year , int month){ int daysofyear = 0; int daysofmonth = 0; for(int i = 1900;i < year;i++){ daysofyear += isLoopYear(i)? 366:365; } for(int i = 1; i < month; i++){ daysofmonth += getDaysOfMonth(year,i); } return daysofyear+daysofmonth; } /** * 利用總天數(shù)模7取余,得到所需要打印的空格數(shù) **/ public static int getSpace(int year,int month){ int allSpace = getTotalDays(year,month) % 7; return allSpace; } }
看完上述內(nèi)容,你們對(duì)使用java在對(duì)日歷進(jìn)行打印有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。