1 /**
2 * Copyright 2008 Bryan Ray
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package uk.org.bryanray.testtoys.generator.sequencegenerators;
17
18 import java.text.DecimalFormat;
19 import java.util.List;
20 import java.util.Random;
21
22
23 /**
24 * <DL>
25 * <DT><B>Project:</B></DT>
26 * <DD>TestDataLoader</DD>
27 * <DT><B>Filename:</B></DT>
28 * <DD>RandomNumberGenerator.java</DD>
29 * <DT><B>Creation Date:</B></DT>
30 * <DD>25 May 2008</DD>
31 * </DL>
32 *
33 * A class that generates a random sequence of numbers. Supports formatting the
34 * number as specified by the user.
35 *
36 * @author Bryan Ray
37 */
38 public class RandomNumberGenerator implements SequenceGenerator {
39 private DecimalFormat decimalFormat;
40 private double minValue;
41 private double maxValue;
42 private String currentValue;
43 private Random random = new Random();
44
45 /**
46 * @param args
47 * A {@link List} of three arguments:
48 * <ol>
49 * <li>A pattern that defines how a {@link DecimalFormat} will
50 * format the number.</li>
51 * <li>A minimum value to be generated.</li>
52 * <li>A maximum value to be generated.</li>
53 * </ol>
54 */
55 public RandomNumberGenerator(List<String> args) {
56 if (3 == args.size()) {
57 String pattern = args.get(0);
58 if (null != pattern && !"".equals(pattern)) {
59 decimalFormat = new DecimalFormat(pattern);
60 } else {
61 decimalFormat = new DecimalFormat();
62 }
63
64 double minValue = Double.parseDouble(args.get(1));
65 double maxValue = Double.parseDouble(args.get(2));
66 if (maxValue >= minValue) {
67 this.minValue = minValue;
68 this.maxValue = maxValue;
69 next();
70 } else {
71 throw new IllegalArgumentException(
72 "Max value exceeds min value.");
73 }
74 } else {
75 throw new IllegalArgumentException(
76 "Incorrect arguments: minValue, maxValue.");
77 }
78 }
79
80 /**
81 * {@inheritDoc}
82 */
83 public void next() {
84 currentValue = decimalFormat.format(random.nextDouble()
85 * (maxValue - minValue) + minValue);
86 }
87
88 /**
89 * {@inheritDoc}
90 */
91 public String value() {
92 return currentValue;
93 }
94 }