閏年を求めるプログラム
public class sample1 { public static void main(String[] args) throws Exception { sample1 sample = new sample1(); String ans = sample.test6(2004); System.out.println(ans); ans = sample.test7(1900); System.out.println(ans); System.out.println(sample.test7(2000)); System.out.println(sample.test7(2004)); } private String test7(int year) throws Exception { if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { return "閏年"; } return "閏年ではない"; } return "閏年"; } return "閏年ではない"; } private String test6(int year) throws Exception { if (year % 4 == 0 && ((!(year % 100 == 0)) || year % 400 == 0)) { return "閏年"; } return "閏年ではない"; } }
なんとなく、メソッドを使ってみる。
べつに、メソッドを使う意味はあんまりないが、2通りのパターンを見せたくこのようにした。
まあ、test7()メソッドはif文の入れ子にしているのだがこれ自体はいいのだが、return文が4つもあってよろしくない。まあ、test6もよろしい書き方でないのは同じだが。
public class sample1 { public static void main(String[] args) throws Exception { int year = 2000; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { System.out.println("閏年"); } else { System.out.println("閏年ではない"); } } else { System.out.println("閏年"); } } else { System.out.println("閏年ではない"); } } }
mainメソッドに書くならこうですね。
if文のネストの形で書いてみました。
public class sample1 { public static void main(String[] args) throws Exception { int year = 2000; if (year % 4 == 0 && ((!(year % 100 == 0)) || year % 400 == 0)) { System.out.println("閏年"); } else { System.out.println("閏年ではない"); } } }