根据如下文法(0)E'→E(1)E→E+T(2)E→T(3)T→TF(4)T→F(5)F→(E)(6)F→id,给出串id*id+id的分析 过程,格式为最右,用Java代码实现
时间: 2024-06-09 11:05:12 浏览: 57
分析过程如下:
```
步骤 分析栈 剩余输入串 所用产生式
1 $E' id*id+id$ E' → E
2 $E id*id+id$ E → T + E
3 $T+E id*id+id$ T → F
4 $F+E id*id+id$ F → id
5 id+E *id+id$ 匹配id
6 id+T *id+id$ T → F
7 id+F+T *id+id$ F → id
8 id+id+T *id+id$ 匹配id
9 id+T +id$ 匹配+
10 id+F+T +id$ F → id
11 id+id+T +id$ 匹配id
12 id+T id$ 匹配id
13 id+F+T id$ F → id
14 id+id+T id$ 匹配id
15 id+F id$ T → F
16 id id$ F → id
17 匹配完成
```
Java代码实现如下:
```java
import java.util.Stack;
public class SyntaxAnalyzer {
private static final String[] productions = {
"",
"E → E+T",
"E → T",
"T → TF",
"T → F",
"F → (E)",
"F → id"
};
private static final int[][] actionTable = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 2, 1, 0, 2, 0, 0, 1, 0, 1},
{0, 4, 4, 3, 4, 0, 0, 4, 0, 4},
{0, 6, 6, 0, 6, 0, 0, 6, 0, 6},
{0, 0, 0, 0, 0, 5, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 7, 8, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 9, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 10, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 11}
};
private static final int[][] gotoTable = {
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 12},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
private static final String input = "id*id+id$";
private static Stack<Integer> stateStack = new Stack<>();
private static Stack<Character> symbolStack = new Stack<>();
public static void main(String[] args) {
stateStack.push(0);
symbolStack.push('$');
int i = 0;
while (i < input.length()) {
int s = stateStack.peek();
char a = input.charAt(i);
int action = actionTable[s][getInputIndex(a)];
if (action == 0) {
System.out.println("Error");
return;
} else if (action < 100) {
stateStack.push(action);
symbolStack.push(a);
i++;
} else if (action < 200) {
int p = action - 100;
String production = productions[p];
String[] rightSymbols = production.split(" → ")[1].split("");
for (int j = 0; j < rightSymbols.length; j++) {
stateStack.pop();
symbolStack.pop();
}
int t = stateStack.peek();
symbolStack.push(production.charAt(0));
stateStack.push(gotoTable[t][getNonterminalIndex(production.charAt(0))]);
}
}
System.out.println("Accept");
}
private static int getInputIndex(char c) {
if (c == 'i') {
return 0;
} else if (c == '+') {
return 1;
} else if (c == '*') {
return 2;
} else if (c == '(') {
return 3;
} else if (c == ')') {
return 4;
} else if (c == '$') {
return 5;
} else {
return -1;
}
}
private static int getNonterminalIndex(char c) {
if (c == 'E') {
return 0;
} else if (c == 'T') {
return 1;
} else if (c == 'F') {
return 2;
} else {
return -1;
}
}
}
```
阅读全文