samples/composition/src-api2.0-enum/api/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:58:05 +0200
changeset 152 eb6f29070331
parent 151 8a1e5fd8e077
child 184 6b2cd8df14c0
permissions -rw-r--r--
Checking that all examples pair the opening and closing brackets
jtulach@151
     1
package api;
jtulach@151
     2
jtulach@151
     3
/** Class to simplify arithmetical operations, improved version to compute
jtulach@151
     4
 * the sum for ranges, but only if one uses the new constructor to indicate
jtulach@151
     5
 * need for new version.
jtulach@151
     6
 *
jtulach@151
     7
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jtulach@151
     8
 * @version 2.0
jtulach@151
     9
 */
jtulach@151
    10
// BEGIN: design.composition.arith2.0.enum
jtulach@151
    11
public class Arithmetica {
jtulach@151
    12
    private final Version version;
jtulach@151
    13
    public enum Version { VERSION_1_0, VERSION_2_0 }
jtulach@151
    14
    
jtulach@151
    15
    public Arithmetica() {
jtulach@151
    16
        this(Version.VERSION_1_0);
jtulach@151
    17
    }
jtulach@151
    18
    public Arithmetica(Version version) {
jtulach@151
    19
        this.version = version;
jtulach@151
    20
    }
jtulach@151
    21
jtulach@151
    22
    public int sumRange(int from, int to) {
jtulach@151
    23
        switch (version) {
jtulach@151
    24
            case VERSION_1_0:
jtulach@151
    25
                return sumRange1(from, to);
jtulach@151
    26
            case VERSION_2_0:
jtulach@151
    27
                return sumRange2(from, to);
jtulach@151
    28
            default:
jtulach@151
    29
                throw new IllegalStateException();
jtulach@151
    30
        }
jtulach@151
    31
    }
jtulach@152
    32
// FINISH: design.composition.arith2.0.enum
jtulach@151
    33
    
jtulach@151
    34
    public int sumTwo(int one, int second) {
jtulach@151
    35
        return one + second;
jtulach@151
    36
    }
jtulach@151
    37
    
jtulach@151
    38
    public int sumAll(int... numbers) {
jtulach@151
    39
        int sum = numbers[0];
jtulach@151
    40
        for (int i = 1; i < numbers.length; i++) {
jtulach@151
    41
            sum = sumTwo(sum, numbers[i]);
jtulach@151
    42
        }
jtulach@151
    43
        return sum;
jtulach@151
    44
    }
jtulach@151
    45
    
jtulach@151
    46
jtulach@151
    47
    private int sumRange1(int from, int to) {
jtulach@151
    48
        int len = to - from;
jtulach@151
    49
        int[] array = new int[len + 1];
jtulach@151
    50
        for (int i = 0; i <= len; i++) {
jtulach@151
    51
            array[i] = from + i;
jtulach@151
    52
        }
jtulach@151
    53
        return sumAll(array);
jtulach@151
    54
    }
jtulach@151
    55
    
jtulach@151
    56
    private int sumRange2(int from, int to) {
jtulach@151
    57
        return (from + to) * (to - from + 1) / 2;
jtulach@151
    58
    }
jtulach@151
    59
}