题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以7月9日为例,应该先把前两个月的加起来,然后再加上9天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。
1 package com.li.FiftyAlgorthm; 2 3 import java.util.Scanner; 4 5 /** 6 * 题目:输入某年某月某日,判断这一天是这一年的第几天? 7 * 程序分析:以7月9日为例,应该先把前两个月的加起来,然后再加上9天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。 8 * 9 * @author yejin10 */11 public class YearMonthDay {12 public static void main(String[] args) {13 int year, month, day;14 int days = 0;15 int d = 0;16 17 YearMonthDay fymd = new YearMonthDay();18 19 System.out.print("Input the year:");20 year = fymd.input();21 System.out.print("Input the month:");22 month = fymd.input();23 System.out.print("Input The Day:");24 day = fymd.input();25 26 if (year < 0 || month < 0 || month > 12 || day < 0 || day > 31) {27 System.out.println("Input error, please run this program again!");28 System.exit(0);29 }30 for (int i = 1; i < month; i++) {31 switch (i) {32 case 1:33 case 3:34 case 5:35 case 7:36 case 8:37 case 10:38 case 12:39 days = 31;40 // d += days;41 break;42 case 4:43 case 6:44 case 9:45 case 11:46 days = 30;47 // d += days;48 break;49 case 2:50 if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {51 days = 29;52 } else {53 days = 28;54 }55 // d += days;56 break;57 }58 59 d += days;60 61 }62 System.out.println(year + ":" + month + ":" + day + "是今年的第" + (d + day)63 + "天。");64 }65 66 public int input() {67 int value = 0;68 Scanner s = new Scanner(System.in);69 value = s.nextInt();70 return value;71 }72 }