天天看點

萬年曆學習筆記

萬年曆學習筆記

import java.util.Scanner;

public class Test1demo {

//判斷是否是閏年

public static boolean isRun(int year)

{

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) 

return true;

}

else

return false;

//判斷年份和月份,還回該月的總天數

public static int getMonthDays(int year,int month) {

int days = 31;

switch (month) {

case 4:

case 6:

case 9:

case 11:

days = 30;

break;

case 2:

if(isRun(year))

days = 29;

else {

days = 28;

return days;

//計算給定年份和月份,計算這個月與第一天1900.1.1過了多少天

public static int getTotalDays(int year, int month)

int totalDays = 0;

for (int i = 1900; i < year; i++) {

totalDays += 366;

totalDays += 365;

for(int i = 1; i < month ; i++)

totalDays += getMonthDays(year, i);

return totalDays;

public static void main(String[] args) {

int year;

int month;

int day;  //  這個月

int totalDays; //這個月第一天與1900.1.1有多少天

int iCount = 0 ;// 計數器,用來決定是否換行

int monthDays ; // 表示該月數

Scanner in = new Scanner(System.in);

System.out.println("*************歡迎使用萬年曆***********");

System.out.println("請輸入年份");

year = in.nextInt();

System.out.println("請輸入月份");

month = in.nextInt();

System.out.println("你輸入的年月是:" +year+"年"+month+"月");

if (isRun(year))

System.out.println(year+"年"+"是閏年");

System.out.println(year+"年"+"是平年");

monthDays = getMonthDays(year, month); //獲得月總天數

totalDays = getTotalDays(year, month); //獲得年總天數

totalDays++; // 獲得多少天

day = totalDays%7; //得到星期幾

System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t");

for(int i = 0; i < day; i++)

System.out.print("\t");

iCount++;

for(int i = 1; i <= monthDays; i++)

System.out.print(i+"\t");

if (iCount %7 == 0) {

System.out.println();

本文轉自 知止内明 51CTO部落格,原文連結:http://blog.51cto.com/357712148/1982907,如需轉載請自行聯系原作者

繼續閱讀