samples/composition/src-api2.0-compat/api/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 10:04:53 +0200
changeset 210 acf2c31e22d4
parent 209 1c999569643b
permissions -rw-r--r--
Merge: Geertjan's changes to the end of the chapter
     1 package api;
     2 
     3 /** Class to simplify arithmetical operations, improved version to compute
     4  * the sum for ranges, but only if one uses the new constructor to indicate
     5  * need for new version.
     6  *
     7  * @author Jaroslav Tulach <jtulach@netbeans.org>
     8  * @version 2.0
     9  */
    10 // BEGIN: design.composition.arith2.0.compat
    11 public class Arithmetica {
    12     private final int version;
    13     
    14     public Arithmetica() {
    15         this(1);
    16     }
    17     public Arithmetica(int version) {
    18         this.version = version;
    19     }
    20     
    21     public int sumTwo(int one, int second) {
    22         return one + second;
    23     }
    24     
    25     public int sumAll(int... numbers) {
    26         if (numbers.length == 0) {
    27             return 0;
    28         }
    29         int sum = numbers[0];
    30         for (int i = 1; i < numbers.length; i++) {
    31             sum = sumTwo(sum, numbers[i]);
    32         }
    33         return sum;
    34     }
    35     
    36     public int sumRange(int from, int to) {
    37         switch (version) {
    38             case 1: return sumRange1(from, to);
    39             case 2: return sumRange2(from, to);
    40             default: throw new IllegalStateException();
    41         }
    42     }
    43 
    44     private int sumRange1(int from, int to) {
    45         int len = to - from;
    46         if (len < 0) {
    47             len = -len;
    48             from = to;
    49         }
    50         int[] array = new int[len + 1];
    51         for (int i = 0; i <= len; i++) {
    52             array[i] = from + i;
    53         }
    54         return sumAll(array);
    55     }
    56     
    57     private int sumRange2(int from, int to) {
    58         return (from + to) * (Math.abs(to - from) + 1) / 2;
    59     }
    60 }
    61 // END: design.composition.arith2.0.compat