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
     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         int sum = numbers[0];
    40         for (int i = 1; i < numbers.length; i++) {
    41             sum = sumTwo(sum, numbers[i]);
    42         }
    43         return sum;
    44     }
    45     
    46 
    47     private int sumRange1(int from, int to) {
    48         int len = to - from;
    49         int[] array = new int[len + 1];
    50         for (int i = 0; i <= len; i++) {
    51             array[i] = from + i;
    52         }
    53         return sumAll(array);
    54     }
    55     
    56     private int sumRange2(int from, int to) {
    57         return (from + to) * (to - from + 1) / 2;
    58     }
    59 }