以下3つのJavaプログラムを実行したとき、想定とは異なる結果になりました。
想定していた結果:
計算開始
comb(5, 0)=1
comb(5, 3)=10
comb(5, 2)=10
NegativeNumberException was thrown: -3! can't be calculated.
BadCombinationException was thrown: 5C6 can't be calculated.
計算終了
実際の実行結果:
:~/java$ java Comb
計算開始
comb(5, 0) = 1
comb(5, 3) = 10
NegativeNumberException was thrown: -3! can't be calculated.
疑問点
なぜ以下の行がそれぞれ出力されなかったのかを知りたいです。お願いします。
comb(5, 2)=10
BadCombinationException was thrown: 5C6 can't be calculated.
計算終了
対象のプログラム:
public class NegativeNumberException extends Exception {
public NegativeNumberException() {
super();
}
public NegativeNumberException(String message) {
super(message);
}
}
public class BadCombinationException extends Exception {
public BadCombinationException() {
super();
}
public BadCombinationException(String message) {
super(message);
}
}
public class Comb {
public static int fact(int n) throws NegativeNumberException {
if (n < 0) { // 負の数の階乗
// エラーなので、例外を作成して投げる
throw new NegativeNumberException(n + "! can't be calculated.");
}
else if (n == 0) {
return 1;
}
else {
return n*fact(n-1);
}
}
public static int comb(int n, int k)
throws NegativeNumberException, BadCombinationException {
if (n < k) {
throw new BadCombinationException(n + " C " + k
+ " can't be calculated.");
}
/* nCk = n!/((n-k)!k!) */
return fact(n)/(fact(n-k)*fact(k));
}
/** テスト用mainメソッド */
public static void main(String args[]) {
try {
System.out.println("計算開始");
int result;
result = Comb.comb(5, 0);
System.out.println("comb(5, 0) = " + result);
result = Comb.comb(5, 3);
System.out.println("comb(5, 3) = " + result);
result = Comb.comb(5, -3);
System.out.println("comb(5, -3) = " + result);
result = Comb.comb(5, 2);
System.out.println("comb(5, 2) = " + result);
result = Comb.comb(5, 6);
System.out.println("comb(5, 6) = " + result);
System.out.println("計算終了");
}
catch (NegativeNumberException e) {
System.err.println("NegativeNumberException was thrown: "
+ e.getMessage());
}
catch (BadCombinationException e) {
System.err.println("BadCombinationException was thrown: "
+ e.getMessage());
}
}
}