Java - アサーション


■ページ目次

Top

■アサーション

Top
■アサーションの形式
Top
■アサーションの有効化と無効化
Top
■javacコマンドのオプション
Top
■javaコマンドのオプション
Top
■条件付コンパイル
Top
■(参考) java.lang.ClassLoaderクラスによる有効化
Top

■契約による設計

Top
■不変条件
Top
■事前条件
Top
■事後条件
Top
■実習
  1. 上記の代数的な余りを求めるアプリケーションAssertion51.javaを作成してください。
    1. public class Assertion51 {
    2. static int aRemainder(int x, int y) {
    3. assert y != 0: "Zero divide."; // 事前条件(ゼロ除算)
    4. int r = 0;
    5. if (x >= 0) {
    6. r = x % y;
    7. } else if (x < 0 ) {
    8. r = x % y + Math.abs(y);
    9. } else {
    10. assert false: "Execution should never reach this point."; // 不変条件(到達不能)
    11. }
    12. assert r >= 0 && r < y: "Remainder is out of range."; // 事後条件(余りが範囲外)
    13. return r;
    14. }
    15. public static void main(String[] args) {
    16. int x = Integer.parseInt(args[0]);
    17. int y = Integer.parseInt(args[1]);
    18. System.out.print("aRemainder(" + x + ", " + y + ") = " + aRemainder(x, y));
    19. System.out.println(", " + x + " % " + y + " = " + (x % y));
    20. System.out.print("aRemainder(" + x + ", " + -y + ") = " + aRemainder(x, -y));
    21. System.out.println(", " + x + " % " + -y + " = " + (x % -y));
    22. System.out.print("aRemainder(" + -x + ", " + y + ") = " + aRemainder(-x, y));
    23. System.out.println(", " + -x + " % " + y + " = " + (-x % y));
    24. System.out.print("aRemainder(" + -x + ", " + -y + ") = " + aRemainder(-x, -y));
    25. System.out.println(", " + -x + " % " + -y + " = " + (-x % -y));
    26. }
    27. }
    $ javac -source 1.4 Assertion51.java
    
    $ java -ea Assertion51 10 3
    aRemainder(10, 3) = 1, 10 % 3 = 1
    aRemainder(10, -3) = 1, 10 % -3 = 1
    aRemainder(-10, 3) = 2, -10 % 3 = -1
    aRemainder(-10, -3) = 2, -10 % -3 = -1
    
    $ java -ea Assertion51 10 0
    Exception in thread "main" java.lang.AssertionError: Zero divide.
            at Assertion51.aRemainder(Assertion51.java:3)
            at Assertion51.main(Assertion51.java:20)
    
Top

inserted by FC2 system