测试员代码链接 :http://www.cnblogs.com/lingzhiliu/p/6600653.html
问题与建议: if...else 语句过多
package lib; import java.util.Scanner; public class nextDate { static String nextdate(int year, int month, int day) { // 闰年 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) { if (day == 31) { day = 1; month++; } else day++; } else if (month == 2) { if (day == 29) { day = 1; month++; } else day++; } else if (month == 12) { if (day == 31) { day = 1; month = 1; year++; } else day++; } else if (month == 4 || month == 6 || month == 9 || month == 11) { if (day == 30) { day = 1; month++; } else day++; } } else// 平年 { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) { if (day == 31) { day = 1; month++; } else day++; } else if (month == 2) { if (day == 28) { day = 1; month++; } else day++; } else if (month == 12) { if (day == 31) { day = 1; month = 1; year++; } else day++; } else if (month == 4 || month == 6 || month == 9 || month == 11) { if (day == 30) { day = 1; month++; } else day++; } } String Year = year + ""; String Month = month + ""; String Day = day + ""; return Year + "年" + Month + "月" + Day + "日"; } public static void main(String[] args) { String tmp = "0"; int month = 0, year = 0, day = 0; String date = " "; while (true) { Scanner sc = new Scanner(System.in); System.out.println("请输入日期(以1个空格区分年月日)"); try { String str = sc.nextLine(); String[] st = str.split(" "); year = Integer.parseInt(st[0]); month = Integer.parseInt(st[1]); day = Integer.parseInt(st[2]); } catch (Exception e) { System.out.print("输入有误重新输入"); continue; } if (year < 1912 || year > 2050) { System.out.println("年份超过范围"); continue; } else if (month > 12 || month < 1) { System.out.println("月份超过范围"); continue; } // 日期有效判断 else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) { if (day > 31 || day < 1) { System.out.println("日期超过范围"); continue; } } else if (month == 4 || month == 6 || month == 9 || month == 11) { if (day > 30 || day < 1) { System.out.println("日期超过范围"); continue; } } else if (month == 2) { if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { if (day < 1 || day > 29) { System.out.println("日期超过范围"); continue; } } else { if (day < 1 || day > 28) { System.out.println("日期超过范围"); continue; } } } date = nextdate(year, month, day); System.out.println("下一天是 "); System.out.print(date); System.out.println("\n是否停止 1 Or -1 -1为停止"); tmp = sc.nextLine(); } } }
心得
增加了输入判定,输入错误会重新输入,对于覆盖判定和语句判定有了进一步的了解。
时间: 2024-12-19 08:04:18