階乗の計算に自作の例外処理を加える

概要

コマンドラインで指定した数の階乗を計算して表示する。
計算結果が負の値になる場合はその旨を表示する。

class Factorial {
    private int value;    // 階乗を求めたい値
    private int factorial;// 階乗の値

    public Factorial(int value) throws FactorialException {
        this.value = value;
        System.out.println(value + "の階乗計算のオブジェクトを生成しました。");
        if (value < 0) {
            throw new FactorialException(value, "値" + value + "の階乗計算に失敗しました。");
        }
    }

    public void execute(int value) throws FactorialException {
        int temp = value;
        this.factorial = temp;
        temp--;
        while (temp > 0) {
            this.factorial = this.factorial * temp;
            temp--;
        }
        if (factorial <= 0) {
            throw new FactorialException(value, "値" + value + "の階乗計算に失敗しました。");
        }
    }

    @Override
    public String toString() {
        return "値" + this.value + "の階乗は" + this.factorial + "です。";
    }
}

class FactorialException extends Exception {
    public FactorialException(int value, String message) {
        super(message);
        if (value < 0) {
            System.out.println("負の値の階乗は計算できません。");
        } else {
            System.out.println("計算可能範囲を超えました。");
        }
    }
}

public class FactorialTest {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("コマンドライン引数の指定がありません。");
            System.exit(1);
        }
        int value;
        try {
            value = Integer.parseInt(args[0]);
            Factorial f = new Factorial(value);
            f.execute(value);
            System.out.println(f);
        } catch (FactorialException e) {
            System.out.println("演算上の例外発生のため、階乗の計算が出来ませんでした。");
        } catch (NumberFormatException e) {
            System.out.println("引数で指定した" + args[0] + "は整数に変換できません。");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("プログラムを終了します。");
    }
}

実行結果1(引数に-3)

  • 3の階乗計算のオブジェクトを生成しました。

負の値の階乗は計算できません。
演算上の例外発生のため、階乗の計算が出来ませんでした。
プログラムを終了します。

実行結果2(引数指定なし)

コマンドライン引数の指定がありません。

実行結果3(引数にabc)

引数で指定したabcは整数に変換できません。
プログラムを終了します。

実行結果4(引数に5)

5の階乗計算のオブジェクトを生成しました。
値5の階乗は120です。
プログラムを終了します。

実行結果5(引数に17→int型の範囲を超えているので計算結果が負になる)

17の階乗計算のオブジェクトを生成しました。
計算可能範囲を超えました。
演算上の例外発生のため、階乗の計算が出来ませんでした。
プログラムを終了します。

プログラマの数学

プログラマの数学