samples/composition/src-api2.0-property/api/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:58:05 +0200
changeset 152 eb6f29070331
parent 149 eb52f31b18f4
child 184 6b2cd8df14c0
permissions -rw-r--r--
Checking that all examples pair the opening and closing brackets
     1 package api;
     2 
     3 /** Class to simplify arithmetical operations, improved version to compute
     4  * the sum for ranges, but only if the virtual machine is configured to
     5  * run in incompatible mode.
     6  *
     7  * @author Jaroslav Tulach <jtulach@netbeans.org>
     8  * @version 2.0
     9  */
    10 // BEGIN: design.composition.arith2.0.property
    11 public class Arithmetica {
    12     public int sumTwo(int one, int second) {
    13         return one + second;
    14     }
    15     
    16     public int sumAll(int... numbers) {
    17         int sum = numbers[0];
    18         for (int i = 1; i < numbers.length; i++) {
    19             sum = sumTwo(sum, numbers[i]);
    20         }
    21         return sum;
    22     }
    23     
    24     public int sumRange(int from, int to) {
    25         // BEGIN: design.composition.arith2.0.property.if
    26         if (Boolean.getBoolean("arithmetica.v2")) {
    27             return sumRange2(from, to);
    28         } else {
    29             return sumRange1(from, to);
    30         }
    31         // END: design.composition.arith2.0.property.if
    32     }
    33 
    34     private int sumRange1(int from, int to) {
    35         int len = to - from;
    36         int[] array = new int[len + 1];
    37         for (int i = 0; i <= len; i++) {
    38             array[i] = from + i;
    39         }
    40         return sumAll(array);
    41     }
    42     
    43     private int sumRange2(int from, int to) {
    44         return (from + to) * (to - from + 1) / 2;
    45     }
    46 }
    47 // END: design.composition.arith2.0.property