关于判断闰年问题,我的思路是首先判断输入是否为合法输入,在输入合法的基础上才可以判断是否为闰年,判断输入是否异常代码如下:
public static void main(String[] args) { String s = " "; System.out.println("请输入一个年份:"); //输入年份 try { BufferedReader in = new BufferedReader(new InputStreamReader( System.in)); s = in.readLine(); } catch (IOException e) { } int year = Integer.parseInt(s); Leadyear aaa = new Leadyear(); boolean leadyear = aaa.judgeyear(year); aaa.printLeadyear(year, leadyear); } 基于上述已经判断输入合法,进行如下判断输入年份是否为闰年: private boolean judgeyear(int year) { boolean leadyear; if (year % 4 == 0 && year % 100 != 0) { leadyear = true; } else if (year % 400 == 0) { leadyear = true; } else leadyear = false; return leadyear; }
最后打印结果如下:
private void printLeadyear(int year, boolean leadyear) { if (leadyear) System.out.println(year + "是闰年!"); else System.out.println(year + "不是闰年!"); } }
测试用例:
编号 | 输入 | 输出 |
1 | 2012 | 是闰年 |
2 | 2004 | 是闰年 |
3 | 1999 | 不是闰年 |