【题目描述】
Enter a certain day of a year to determine which day is it of the year?
【题目翻译】
输入某年某月某日,判断这一天是这一年的第几天?
【解题思路】
以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。
【本题答案】
import java.io.BufferedReader; import java.io.InputStreamReader; /** * Description:<br> 输入某年某月某日,判断这一天是这一年的第几天? * <br> * Remark:<br> * <br> * Date:2018/1/31 * * @author yesr * @version 0.0.1 */ public class Test0131 { private static boolean isLeapYear(int y){ return (y % 4 == 0 && y % 100 != 100) || y % 400 == 0; } private static int sumDays(int y, int m, int d){ int[] MonthDays = {31,28,31,30,31,30,31,31,30,31,30,31}; if(isLeapYear(y)) MonthDays[1] = 29; int ans = 0; for(int i=0; i<m-1; i++){ ans = ans + MonthDays[i]; } return ans + d; } public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String in = null; try { System.out.println("请输入年月日,例如:2014-01-01"); in = br.readLine(); } catch (Exception e) { System.out.println("格式错误"); } assert in != null; int y = Integer.parseInt(in.substring(0, in.indexOf('-'))); int m = Integer.parseInt(in.substring(in.indexOf('-') + 1, in.lastIndexOf('-'))); int d = Integer.parseInt(in.substring(in.lastIndexOf('-') + 1)); while (!isLeapYear(y)) { if ((d > 31)||(m > 12)||(d == 29)||(d == 30)||(d == 31)) { System.out.print("日期不存在,请输入正确日期"); break; } else { System.out.println(sumDays(y, m, d)); break; } } while (isLeapYear(y)) { if ((d > 31)||(m > 12)||(m == 2)&&(d == 30)||(m == 2)&&(d == 31)) { System.out.println("日期不存在,请输入正确日期"); break; } else { System.out.println(sumDays(y, m, d)); break; } } } }
【运行结果】