samples/composition/src-api2.0-compat/api/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:58:05 +0200
changeset 152 eb6f29070331
parent 147 e81ff4f391b8
child 184 6b2cd8df14c0
permissions -rw-r--r--
Checking that all examples pair the opening and closing brackets
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@147
    26
        int sum = numbers[0];
jtulach@147
    27
        for (int i = 1; i < numbers.length; i++) {
jtulach@147
    28
            sum = sumTwo(sum, numbers[i]);
jtulach@147
    29
        }
jtulach@147
    30
        return sum;
jtulach@147
    31
    }
jtulach@147
    32
    
jtulach@147
    33
    public int sumRange(int from, int to) {
jtulach@147
    34
        switch (version) {
jtulach@147
    35
            case 1: return sumRange1(from, to);
jtulach@147
    36
            case 2: return sumRange2(from, to);
jtulach@147
    37
            default: throw new IllegalStateException();
jtulach@147
    38
        }
jtulach@147
    39
    }
jtulach@147
    40
jtulach@147
    41
    private int sumRange1(int from, int to) {
jtulach@147
    42
        int len = to - from;
jtulach@147
    43
        int[] array = new int[len + 1];
jtulach@147
    44
        for (int i = 0; i <= len; i++) {
jtulach@147
    45
            array[i] = from + i;
jtulach@147
    46
        }
jtulach@147
    47
        return sumAll(array);
jtulach@147
    48
    }
jtulach@147
    49
    
jtulach@147
    50
    private int sumRange2(int from, int to) {
jtulach@147
    51
        return (from + to) * (to - from + 1) / 2;
jtulach@147
    52
    }
jtulach@152
    53
}
jtulach@147
    54
// END: design.composition.arith2.0.compat