-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecimalParser.java
More file actions
72 lines (57 loc) · 1.37 KB
/
DecimalParser.java
File metadata and controls
72 lines (57 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.InputStream;
import java.io.InputStreamReader;
class DecimalParser {
public static void main(String args[]) throws Exception {
if (args.length==0) {
System.out.println("Usage: java NumberParser value");
System.exit(1);
}
double val = MyParseDecimal(args[0]);
System.out.println("Value="+val);
}
enum StateDecimal { SSTART, SINTEGER, SDECIMAL, SEND };
public static double MyParseDecimal(String s) throws Exception {
StateDecimal state;
state = StateDecimal.SSTART;
int i = 0;
double divider = 10;
double value = 0;
while ( i < s.length() && state != StateDecimal.SEND) {
char ch = s.charAt(i);
switch (state) {
case SSTART:
if (Character.isDigit(ch)) {
state = StateDecimal.SINTEGER;
value = Character.getNumericValue(ch);
i++;
}
else {
throw new Exception("Bad format");
}
break;
case SINTEGER:
if (Character.isDigit(ch)) {
state = StateDecimal.SINTEGER;
value = 10.0*value + Character.getNumericValue(ch);
i++;
}
else if (ch == '.') {
state = StateDecimal.SDECIMAL;
i++;
}
break;
case SDECIMAL:
if (Character.isDigit(ch)) {
value = value + Character.getNumericValue(ch)/divider;
divider = divider * 10;
i++;
}
else {
throw new Exception("Bad format");
}
break;
}
}
return value;
}
}