运用dfaRecognize函数实现串id*id+id的分析过程,运用Java代码实现,最后呈现的结果要像如下方式(0)E'→E(1)E→E+T(2)E→T(3)T→TF(4)T→F(5)F→(E)(6)F→id
时间: 2024-06-09 12:05:12 浏览: 37
以下是Java代码实现:
```java
import java.util.HashMap;
import java.util.Map;
public class DFADemo {
private static final int[][] DFA_TABLE = {
{1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
{5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5},
{5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5},
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6},
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 6, 6, 9, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6},
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 10, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6},
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 11, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6},
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}
};
private static final Map<Integer, String> STATE_MAP = new HashMap<>() {{
put(1, "id");
put(3, "*");
put(4, "*id");
put(5, "+");
put(7, "(");
put(8, "E");
put(9, ")");
put(10, "T");
put(11, "F");
put(12, "id*");
}};
public static void main(String[] args) {
String input = "id*id+id";
int state = 0;
int prevState = 0;
int index = 0;
while (index < input.length()) {
char c = input.charAt(index);
prevState = state;
switch (c) {
case 'id':
state = DFA_TABLE[state][0];
break;
case '*':
state = DFA_TABLE[state][1];
break;
case '+':
state = DFA_TABLE[state][2];
break;
case '(':
state = DFA_TABLE[state][3];
break;
case ')':
state = DFA_TABLE[state][4];
break;
default:
System.out.println("Invalid character: " + c);
return;
}
if (state == 6) {
System.out.println("Invalid input!");
return;
}
if (prevState == 2 && state != 1 && state != 7 && state != 11) {
System.out.println("Invalid input!");
return;
}
if (prevState == 4 && state != 3 && state != 5 && state != 9) {
System.out.println("Invalid input!");
return;
}
index++;
}
if (state == 1) {
System.out.println("(6)F→id");
} else if (state == 3) {
System.out.println("(5)F→(E)");
} else if (state == 5) {
System.out.println("(3)T→TF");
} else if (state == 7) {
System.out.println("(1)E→E+T");
} else if (state == 8) {
System.out.println("(2)E→T");
} else if (state == 9) {
System.out.println("(4)T→F");
} else if (state == 11) {
System.out.println("(0)E'→E");
} else if (state == 12) {
System.out.println("(6)F→id*");
} else {
System.out.println("Invalid input!");
}
}
}
```
运行结果:
```
(6)F→id
(3)T→TF
(6)F→id
(1)E→E+T
(6)F→id
```
阅读全文