回答編集履歴
1
コード修正
answer
CHANGED
@@ -43,37 +43,37 @@
|
|
43
43
|
`4+2=` のようにスペースなしにしたい場合は少し面倒になります。
|
44
44
|
```Java
|
45
45
|
import java.util.Scanner;
|
46
|
-
import java.util.regex.MatchResult;
|
46
|
+
import java.util.regex.*; // Pattern, MatchResult;
|
47
47
|
|
48
48
|
class Test {
|
49
|
-
|
49
|
+
public static void main(String[] args) {
|
50
|
-
|
50
|
+
Scanner sc = new Scanner(System.in);
|
51
|
+
Pattern pat = Pattern.compile("(\d+)\s*(.)\s*(\d+)\s*=");
|
51
|
-
|
52
|
+
while (true) {
|
52
|
-
|
53
|
+
System.out.print(">> ");
|
53
|
-
|
54
|
+
if (!sc.hasNextLine()) break;
|
54
|
-
|
55
|
+
String line = sc.nextLine();
|
55
|
-
|
56
|
+
Scanner sc2 = new Scanner(line);
|
56
|
-
|
57
|
+
try {
|
57
|
-
|
58
|
+
sc2.findInLine(pat);
|
58
|
-
|
59
|
+
MatchResult r = sc2.match();
|
59
|
-
if (r.groupCount() != 3) throw new Exception();
|
60
|
-
|
60
|
+
int x = Integer.parseInt(r.group(1));
|
61
|
-
|
61
|
+
int y = Integer.parseInt(r.group(3));
|
62
|
-
|
62
|
+
int z = 0;
|
63
|
-
|
63
|
+
switch (r.group(2)) {
|
64
|
-
|
64
|
+
case "+": z = x + y; break;
|
65
|
-
|
65
|
+
case "-": z = x - y; break;
|
66
|
-
|
66
|
+
case "*": z = x * y; break;
|
67
|
-
|
67
|
+
case "/": z = x / y; break;
|
68
|
-
|
68
|
+
}
|
69
|
-
|
69
|
+
System.out.println(z);
|
70
|
-
|
70
|
+
}
|
71
|
-
|
71
|
+
catch (Exception e) {
|
72
|
-
|
72
|
+
System.out.println(" Error");
|
73
|
-
|
73
|
+
}
|
74
|
-
|
74
|
+
sc2.close();
|
75
|
-
|
75
|
+
}
|
76
|
-
|
76
|
+
sc.close();
|
77
|
-
|
77
|
+
}
|
78
78
|
}
|
79
79
|
```
|