求給定日期的後一日期【java】

import java.util.Scanner;

/**
 * 給定一個日期,求後一天的日期
 * 
 * @author lm吹夢到西洲
 * @date 2018/5/6
 *
 */
public class NextDate {
	int year, month, day;

	public void getDay(int year, int month, int day) {
		this.year = year;
		this.month = month;
		this.day = day;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 9:
		case 11:
			if (day < 1 || day > 31) {
				System.out.println("天數在1-31之間!");
				System.exit(0);
			} else if (day <= 30) {
				day++;
			} else if (day == 31) {
				month++;
				day = 1;

			}
			System.out.println(year + "/" + month + "/" + day);
			break;
		case 12:
			if (day < 1 || day > 31) {
				System.out.println("天數在1-31之間!");
				System.exit(0);
			} else if (day <= 30) {
				day++;

			} else if (day == 31) {
				year++;
				month = 1;
				day = 1;
			}
			System.out.println(year + "/" + month + "/" + day);
			break;

		case 4:
		case 6:
		case 8:
		case 10:
			if (day < 1 || day > 30) {
				System.out.println("天數在1-30之間!");
				System.exit(0);
			} else if (day <= 29) {
				day++;

			} else if (day == 30) {
				month++;
				day = 1;
				System.out.println(year + "/" + month + "/" + day);
			}
			break;
		case 2:
			if (day < 1 || day > 29) {
				System.out.println("天數在1-29之間!");
				System.exit(0);
			} else if (day <= 27) {
				day++;

			} else if (day == 28) {
				if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
					day++;

				} else {
					month++;
					day = 1;

				}

			} else if (day == 29) {
				if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
					month++;
					day = 1;

				} else {
					System.out.println("平年2月沒有29天!");
					System.exit(0);
				}
			}
			System.out.println(year + "/" + month + "/" + day);
			break;
		default:
			System.out.println("月數在1-12之間!");

		}
	}
}

class Test {
	public static void main(String[] args) {
		NextDate a = new NextDate();
		Scanner date = new Scanner(System.in);
		System.out.println("請輸入年份:");
		int year = date.nextInt();
		System.out.println("請輸入月份:");
		int month = date.nextInt();
		System.out.println("請輸入天數:");
		int day = date.nextInt();
		System.out.println("您輸入的日期爲:" + year + "/" + month + "/" + day);
		System.out.print("後一天的日期爲:");
		a.getDay(year, month, day);

	}
}

運行如下
請輸入年份:

2018

請輸入月份:
5
請輸入天數:
6
您輸入的日期爲:2018/5/6
後一天的日期爲:2018/5/7
------------------------------------------

請輸入年份:
2008
請輸入月份:
2
請輸入天數:
29
您輸入的日期爲:2008/2/29
後一天的日期爲:2008/3/1
--------------------------------------------
請輸入年份:
2009
請輸入月份:
2
請輸入天數:
29
您輸入的日期爲:2009/2/29
後一天的日期爲:平年2月沒有29天!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章