就和写数学题目一样,在做题目之前要先把思路确立下来。可能是我早年做数学的时候老是着急做题目没怎么分析过题目,把这个习惯不自觉地代入了代码的写入当中。习惯的养成使得我即使明白了自己的问题也依然会不断的犯错,看来只有刻意地提醒自己才能够消除这个坏习惯。
这道题目看起来简单,让人觉得一上手就可以了。然而这是最大的陷阱。
package 练习;
import java.util.*;public class 日期问题 {public static void main(String[] args) {Scanner scan = new Scanner(System.in);int[] num = new int[3];int num1;int i = 0;String[] date = scan.nextLine().split("/");int[] ans = new int[3];num[0] = Integer.parseInt(date[0]);num[1] = Integer.parseInt(date[1]);num[2] = Integer.parseInt(date[2]);ans[i] = datefind(num[0],num[1],num[2]);i ++;ans[i] = datefind(num[2],num[0],num[1]);i ++;ans[i] = datefind(num[2],num[1],num[0]);for(i = 0;i < 2;i ++) {for(int j = i + 1;j < 3;j ++) {if(ans[i] == ans[j])ans[i] = 0;}for(i = 0;i < 3;i ++) {if(ans[i] == 0)continue;elseSystem.out.println(ans[i] / 10000 + "-" + ((ans[i] % 10000 - (ans[i] % 100 ) / 100) + "-" + ans[i] % 100);}}}public static int datefind(int year,int month,int days) {if(year > 60 || year < 59)return 0;else if(month < 0 || month > 12)return 0;else if(days <= 0 || days > 31)return 0;if((month == 1 ||month == 3 ||month == 5 ||month == 7 ||month == 8 ||month == 10 ||month == 12 )&& (days > 31 || days <= 0))return 0;if((month == 4 ||month == 6 ||month == 9 ||month == 11) && (days > 30 || days <= 0))return 0;if(month == 2 && (days < 0 || days > 29))return 0;else if(year == 59)year = year + 1900;elseyear = year + 2000;if((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) && days != 29)return 0;return year * 10000 + month * 100 + days;
}}
仔细看看判断条件
if((month == 1 ||month == 3 ||month == 5 ||month == 7 ||month == 8 ||month == 10 ||month == 12 )&& (days > 31 || days <= 0))
if((month == 4 ||month == 6 ||month == 9 ||month == 11) && (days > 30 || days <= 0))
if(month == 2 && (days < 0 || days > 29))
if((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) && days != 29)
days的判断重复了,然而此时我写了十分多的代码所以脑子累得根本分析不出来了,还有return的只有2000的没有1900的了。更不用说代码的核心思想都错了——本来应该是判断时间在不在范围内结果成了判断是不是闰年了。
这都是我不做计划的恶果。