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
     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         int sum = numbers[0];
    27         for (int i = 1; i < numbers.length; i++) {
    28             sum = sumTwo(sum, numbers[i]);
    29         }
    30         return sum;
    31     }
    32     
    33     public int sumRange(int from, int to) {
    34         switch (version) {
    35             case 1: return sumRange1(from, to);
    36             case 2: return sumRange2(from, to);
    37             default: throw new IllegalStateException();
    38         }
    39     }
    40 
    41     private int sumRange1(int from, int to) {
    42         int len = to - from;
    43         int[] array = new int[len + 1];
    44         for (int i = 0; i <= len; i++) {
    45             array[i] = from + i;
    46         }
    47         return sumAll(array);
    48     }
    49     
    50     private int sumRange2(int from, int to) {
    51         return (from + to) * (to - from + 1) / 2;
    52     }
    53 }
    54 // END: design.composition.arith2.0.compat