teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

コード修正

2020/08/29 22:13

投稿

kazuma-s
kazuma-s

スコア8222

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
- public static void main(String[] args) {
49
+ public static void main(String[] args) {
50
- Scanner sc = new Scanner(System.in);
50
+ Scanner sc = new Scanner(System.in);
51
+ Pattern pat = Pattern.compile("(\d+)\s*(.)\s*(\d+)\s*=");
51
- while (true) {
52
+ while (true) {
52
- System.out.print(">> ");
53
+ System.out.print(">> ");
53
- if (!sc.hasNextLine()) break;
54
+ if (!sc.hasNextLine()) break;
54
- String line = sc.nextLine();
55
+ String line = sc.nextLine();
55
- Scanner sc2 = new Scanner(line);
56
+ Scanner sc2 = new Scanner(line);
56
- try {
57
+ try {
57
- sc2.findInLine("(\d+)\s*(.)\s*(\d+)\s*=");
58
+ sc2.findInLine(pat);
58
- MatchResult r = sc2.match();
59
+ MatchResult r = sc2.match();
59
- if (r.groupCount() != 3) throw new Exception();
60
- int x = Integer.valueOf(r.group(1));
60
+ int x = Integer.parseInt(r.group(1));
61
- int y = Integer.valueOf(r.group(3));
61
+ int y = Integer.parseInt(r.group(3));
62
- int z = 0;
62
+ int z = 0;
63
- switch (r.group(2)) {
63
+ switch (r.group(2)) {
64
- case "+": z = x + y; break;
64
+ case "+": z = x + y; break;
65
- case "-": z = x - y; break;
65
+ case "-": z = x - y; break;
66
- case "*": z = x * y; break;
66
+ case "*": z = x * y; break;
67
- case "/": z = x / y; break;
67
+ case "/": z = x / y; break;
68
- }
68
+ }
69
- System.out.println(z);
69
+ System.out.println(z);
70
- }
70
+ }
71
- catch (Exception e) {
71
+ catch (Exception e) {
72
- System.out.println(" Error");
72
+ System.out.println(" Error");
73
- }
73
+ }
74
- sc2.close();
74
+ sc2.close();
75
- }
75
+ }
76
- sc.close();
76
+ sc.close();
77
- }
77
+ }
78
78
  }
79
79
  ```