1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jboss.as.quickstarts.temperatureconverter.ejb;
18
19 import java.text.DecimalFormat;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
22
23
24
25
26
27
28
29
30 public class Temperature {
31
32 public static final double ABSOLUTE_ZERO_C = -273.150;
33 public static final double ABSOLUTE_ZERO_F = -459.670;
34
35
36
37
38 private static Pattern PATTERN = Pattern.compile("^([-+]?\\d*\\.?\\d+)\\s*([cCfF]?)");
39
40
41
42
43
44
45
46 public static Temperature parse(String temperature, Scale defaultScale) {
47 double t;
48 Scale s;
49
50
51
52
53 Matcher matcher = PATTERN.matcher(temperature);
54
55 if (matcher.find()) {
56
57 t = Double.parseDouble(matcher.group(1));
58
59
60 if (!matcher.group(2).isEmpty()) {
61 try {
62 s = Scale.valueOfAbbreviation(matcher.group(2));
63 } catch (IllegalArgumentException e) {
64 throw new IllegalArgumentException("You must provide a valid temperature scale- 'C|F'");
65 }
66 } else {
67 s = defaultScale;
68 }
69 } else {
70 throw new IllegalArgumentException("You must provide a valid temperature to convert- 'XX.XXX'");
71 }
72
73 return new Temperature(t, s);
74 }
75
76 private final double temperature;
77 private final Scale scale;
78
79 public Temperature(double temperature, Scale scale) {
80 this.temperature = temperature;
81 this.scale = scale;
82 }
83
84 public Scale getScale() {
85 return scale;
86 }
87
88 public double getTemperature() {
89 return temperature;
90 }
91
92 @Override
93 public String toString() {
94 return new DecimalFormat("###.###").format(temperature) + " " + scale.getSymbol();
95 }
96
97 }