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