回答編集履歴

1

追記

2023/02/06 15:21

投稿

kazuma-s
kazuma-s

スコア8224

test CHANGED
@@ -48,4 +48,59 @@
48
48
  }
49
49
  }
50
50
  ```
51
+ **追記**
52
+ 演算子の優先順位と括弧の処理も追加した構文解析です。
53
+ ```Java
54
+ import java.util.Scanner;
51
55
 
56
+ class Main {
57
+ public static void main(String[] args) {
58
+ System.out.println("数式を入力してください");
59
+ Scanner scanner = new Scanner(System.in);
60
+ String formula = scanner.nextLine();
61
+ Expr e = new Expr(formula);
62
+ int val = e.syn(0);
63
+ if (e.tok != 0) System.out.println("syntax error");
64
+ else System.out.println(val);
65
+ }
66
+ }
67
+
68
+ class Expr { // 数式クラス (expression)
69
+ String str; int len, pos, val; char tok;
70
+
71
+ Expr(String s) { str = s; len = s.length(); pos = 0; }
72
+
73
+ char lex() { // 字句解析 (lexical analyzer)
74
+ while (pos < len)
75
+ if ((tok = str.charAt(pos++))>='0' && tok<='9') {
76
+ for (val = tok - '0'; pos < len &&
77
+ (tok = str.charAt(pos))>='0' && tok<='9'; pos++)
78
+ val = val * 10 + (tok - '0');
79
+ return tok = '0';
80
+ }
81
+ else if (tok != ' ') return tok;
82
+ return tok = 0; // end of string
83
+ }
84
+
85
+ final static char[] op = { '+', '-', '*', '/' };
86
+
87
+ int syn(int i) { // 構文解析 (syntax analyzer)
88
+ int v;
89
+ if (i < 4)
90
+ for (v = syn(i+2); tok == op[i] || tok == op[i+1]; )
91
+ if (tok == '+') v += syn(i+2);
92
+ else if (tok == '-') v -= syn(i+2);
93
+ else if (tok == '*') v *= syn(i+2);
94
+ else v /= syn(i+2);
95
+ else if (lex() == '0') { v = val; lex(); }
96
+ else if (tok == '(') {
97
+ v = syn(0);
98
+ if (tok == ')') lex();
99
+ else tok = 1;
100
+ }
101
+ else v = tok = 1;
102
+ return v;
103
+ }
104
+ }
105
+ ```
106
+