samples/composition/src-api2.0-property/api/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:57:56 +0200
changeset 148 e762b177d4b0
child 149 eb52f31b18f4
permissions -rw-r--r--
Using Arithmetica for yet another example
     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         if (Boolean.getBoolean("arithmetica.v2")) {
    26             return sumRange2(from, to);
    27         } else {
    28             return sumRange1(from, to);
    29         }
    30     }
    31 
    32     private int sumRange1(int from, int to) {
    33         int len = to - from;
    34         int[] array = new int[len + 1];
    35         for (int i = 0; i <= len; i++) {
    36             array[i] = from + i;
    37         }
    38         return sumAll(array);
    39     }
    40     
    41     private int sumRange2(int from, int to) {
    42         return (from + to) * (to - from + 1) / 2;
    43     }
    44 // END: design.composition.arith2.0.property
    45 }