samples/composition/src-api2.0-enum/api/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 10:04:51 +0200
changeset 209 1c999569643b
parent 206 b1f279a7ec46
child 210 acf2c31e22d4
permissions -rw-r--r--
to the end of daily_life
     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.enum
    11 public class Arithmetica {
    12     private final Version version;
    13     public enum Version { VERSION_1_0, VERSION_2_0 }
    14     
    15     public Arithmetica() {
    16         this(Version.VERSION_1_0);
    17     }
    18     public Arithmetica(Version version) {
    19         this.version = version;
    20     }
    21 
    22     public int sumRange(int from, int to) {
    23         switch (version) {
    24             case VERSION_1_0:
    25                 return sumRange1(from, to);
    26             case VERSION_2_0:
    27                 return sumRange2(from, to);
    28             default:
    29                 throw new IllegalStateException();
    30         }
    31     }
    32 // FINISH: design.composition.arith2.0.enum
    33     
    34     public int sumTwo(int one, int second) {
    35         return one + second;
    36     }
    37     
    38     public int sumAll(int... numbers) {
    39         if (numbers.length == 0) {
    40             return 0;
    41         }
    42         int sum = numbers[0];
    43         for (int i = 1; i < numbers.length; i++) {
    44             sum = sumTwo(sum, numbers[i]);
    45         }
    46         return sum;
    47     }
    48     
    49 
    50     private int sumRange1(int from, int to) {
    51         int len = to - from;
    52         int[] array = new int[len + 1];
    53         for (int i = 0; i <= len; i++) {
    54             array[i] = from + i;
    55         }
    56         return sumAll(array);
    57     }
    58     
    59     private int sumRange2(int from, int to) {
    60         return (from + to) * (to - from + 1) / 2;
    61     }
    62 }