前情提要:
自己慢慢摸索写出的集词法分析、递归下降分析、LL1、波兰式于一体的且带有UI界面的程序。
以下是四个实验目的阐述与结果截图,会贴上最重要的代码。
由于代码有些大,会附有链接收取一点点积分换取完整代码。
实验程序链接
实验一:词法分析
实验目的
通过设计编制调试一个具体的词法分析程序,加深对词法分析原理的理解。并掌握在对程序设计语言源程序进行扫描过程中将其分解为各类单词的词法分析方法。
编制一个读单词过程,从输入的源程序中,识别出各个具有独立意义的单词,即基本保留字、标识符、常数、运算符、分隔符五大类。并依次输出各个单词的内部编码及单词符号自身值。(遇到错误时可显示“Error”,然后跳过错误部分继续显示)
实验截图
实验代码
import javax.swing.JTextArea;
public class LexicalAnalyzer {
static String[] rwtab=new String[]{"main","if","then","while","do","static",
"int","double","struct","break","else",
"long","switch","case","typedef","char",
"return","const","float","short","continue",
"for","void","sizeof"}; //定义的24个关键字,种别码从1开始
static String storage=""; //存储源程序字符串
static StringBuilder token=new StringBuilder(""); //存储单词自身组成的字符串
private char lastchar; //单个读取字符
private int index=0; //单行字符串脚标
private int syn; //种别码
private int row=1;
//分析器
void analyzer(){
token.delete(0, token.length()); //置空token对象,清除
lastchar=storage.charAt(index); //索引指向第0位
if(((lastchar>='a'&&lastchar<='z')||(lastchar>='A'&&lastchar<='Z'))&&index='0'&&lastchar<='9')||(lastchar>='a'&&lastchar<='z')||(lastchar>='A'&&lastchar<='Z'))&&index='0'&&lastchar<='9')||(lastchar>='a'&&lastchar<='z')||(lastchar>='A'&&lastchar<='Z')) {
token.append(lastchar);
}else {
index--;
}
}
syn=2; //默认为识别出的字符串为自定义的标识符,种别码为2
String s=token.toString();
for(int i=0; i='0'&&lastchar<='9')&&index='0'&&lastchar<='9'||lastchar=='.')&&index='0'&&lastchar<='9')||lastchar=='.') {
token.append(lastchar);
}else {
index--;
}
}
syn=3; //整数的种别码为3
}else if(index'){
token.append(lastchar);
index++;
}
}
break;
case '>':
token.append(lastchar);
syn=4;
if(index
实验二:递归下降分析
实验目的
根据某一文法编制调试递归下降分析程序,以便对任意输入的符号串进行分析。本次实验的目的主要是加深对递归下降分析法的理解。
实验截图
实验代码
package Lab;
import java.util.Scanner;
import javax.swing.JTextArea;
public class RecursiveAnalyzer {
static String str = "";
static char sym;
static char t[];
static int j=0;
static JTextArea jta;
public void execute(String str,JTextArea jta) {
this.jta = jta;
this.str=str;
jta.append("编制人: 姓名, 学号, 班级n");
t = str.toCharArray();
sym=t[j++];
p();
E();
//文法
if(sym=='#') {
jta.append(str+" is illegal string!");
}else {
error();
}
}
static void error() {
jta.append(str+" is valid string!n");
return;
}
static void p() {
System.out.print(sym);
}
static void E() {
if(sym == 'e') {
sym=t[j++];
p();
B();}
else if(sym == 'a') {
sym=t[j++];
p();
A();
}
else
error();
}
static void A() {
if(sym=='a') {
sym=t[j++];
p();
}
else if(sym == 'b') {
sym=t[j++];
p();
A();
}
else if(sym=='c') {
sym=t[j++];
p();
B();
}
else
error();
}
static void B() {
if(sym=='d') {
sym=t[j++];
p();
E();
if(sym=='d') {
sym=t[j++];
p();
}
else error();
}
else if(sym=='a') {
sym=t[j++];
p();
C();
}
else
error();
}
static void C() {
if(sym=='e') {
sym=t[j++];
p();
}
else if(sym=='d') {
sym=t[j++];
p();
C();
}
else
error();
}
}
实验三:LL1
实验目的
根据某一文法编制调试LL(1)分析程序,以便对任意输入的符号串进行分析。本次实验的目的主要是加深对预测分析LL(1)分析法的理解。
(1)E->TG
(2)G->+TG|-TG
(3)G->ε
(4)T->FS
(5)S->*FS|/FS
(6)S->ε
(7)F->(E)
(8)F->i
实验截图
实验代码
package Lab;
import java.io.*;
import javax.swing.JTextArea;
public class LL1 {
String Vn[] = {"E", "G", "T", "S", "F"};
String Vt[] = {"i", "+", "-", "*", "/", "(", ")", "#"};
String P[][] = new String[5][8];
String fenxi[] ;
int count = 1;
int count1 = 1;
int count2 = 0, count3 = 0;
boolean flag;
static String str;
static JTextArea jta;
public void setCount(int count, int count1, int count2, int count3){
this.count = count;
this.count1 = count1;
this.count2 = count2;
this.count3 = count3;
flag = false;
}
public void setFenxi() {
fenxi = new String[20];
fenxi[0] = "#";
fenxi[1] = "E";
}
public void setP() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 8; j++)
{
P[i][j] = "null";
}
}
P[0][0] = "->TG";
P[0][5] = "->TG";
P[1][1] = "->+TG";
P[1][2] = "->-TG";
P[1][6] = "->ε";
P[1][7] = "->ε";
P[2][0] = "->FS";
P[2][5] = "->FS";
P[3][1] = "->ε";
P[3][2] = "->ε";
P[3][3] = "->*FS";
P[3][4] = "->/FS";
P[3][6] = "->ε";
P[3][7] = "->ε";
P[4][0] = "->i";
P[4][5] = "->i";
}
public boolean judge() {
//jta.append("judge");
String inputChar = str.substring(0, 1);
boolean flage = false;
if (count1 >= 0) {
for (int i=0; i<6; i++) {
if (fenxi[count1].equals(Vt[i])) {
flage = true;
break;
}
}
}
if (flage) {
if (fenxi[count1].equals(inputChar)) {
if (fenxi[count1].equals("#")&&str.length()==1){
String fenxizhan = "";
for (int i=0; i<=P.length; i++) {
if (fenxi[i] == null) {
break;
} else {
fenxizhan = fenxizhan + fenxi[i];
}
}
jta.append(" " + count);
String countToString = Integer.toString(count);
int farWay = 14 - countToString.length();
for (int k=0; k 1) {
str = str.substring(1, str.length());
} else {
inputChar = str;
}
count++;
judge();
}
}else {
jta.append(" 分析到第" + count + "步时出错!n");
flag = false;
return false;
}
} else {
boolean fla = false;
for (int i=0; i<8; i++) {
if (inputChar.equals(Vt[i])) {
fla = true;
count2 = i;
break;
}
}
if(!fla){
jta.append(" 分析到第" + count + "步时出错!n");
flag = false;
return false;
}
for (int i=0; i<5; i++) {
if (fenxi[count1].equals(Vn[i])) {
count3 = i;
break;
}
}
if (P[count3][count2] != "null") {
String p = P[count3][count2];
String s1 = p.substring(2, p.length());
if (s1.equals("ε")) {
String fenxizhan = "";
for (int i=0; i<=P.length; i++) {
if (fenxi[i] == null) {
break;
} else {
fenxizhan = fenxizhan + fenxi[i];
}
}
jta.append(" " + count);
String countToString = Integer.toString(count);
int farWay = 14 - countToString.length();
for (int k=0; k
实验四:波兰式与四元式及计算(只能进行个位数的计算,两位及以上的有问题,做不出来。)
实验目的
将非后缀式用来表示的算术表达式转换为用逆波兰式来表示的算术表达式,并计算用逆波兰式来表示的算术表达式的值。
实验截图
实验代码
(1)RpnMain类
package Lab;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
import javax.swing.JTextArea;
public class RpnMain {
static StringBuilder sb;
ArrayStack container = new ArrayStack(20);
public boolean isMatch(String s) {
//括号符号栈
Stack charStack = new Stack<>();
//将表达式的字符串转换成数组
char[] charArray = s.toCharArray();
//遍历数组
for (char aChar : charArray) {
if (aChar == '(') {
charStack.push(aChar);
} else if (aChar == ')') {
//如果是 ) , 且栈为空则返回 false
if (charStack.isEmpty()) {
return false;
} else {
if (charStack.peek() == '(') {
charStack.pop();
}
}
}
}
//走到这里, 栈为空则表达式正确
return charStack.empty();
}
public boolean isOperator(char charAt) {
return charAt == '+' || charAt == '-' || charAt == '*' || charAt == '/';
}
public StringBuilder getRpn(String input) {
sb = new StringBuilder();
//运算符栈
Stack opStack = new Stack();
Map opMap = new HashMap(5);
opMap.put('(', 0);
opMap.put('+', 1);
opMap.put('-', 1);
opMap.put('*', 2);
opMap.put('/', 2);
//处理字符串
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(') {
opStack.push('(');
} else if (new RpnMain().isOperator(input.charAt(i))) {
//如果是运算符
char curOp = input.charAt(i);
if (opStack.isEmpty()) {
opStack.push(curOp);
} else if (opMap.get(curOp) > opMap.get(opStack.peek())) {
opStack.push(curOp);
} else {
for (int j = 0; j <= opStack.size(); j++) {
//弹出栈内第一个元素
char ch = opStack.pop();
sb.append(ch);
if (opStack.isEmpty()) {
opStack.push(curOp);
break;
} else if (opMap.get(curOp) > opMap.get(opStack.peek())) {
opStack.push(curOp);
break;
}
}
}
} else if (input.charAt(i) == ')') {
for (int j = 0; j < opStack.size(); j++) {
char c = opStack.pop();
if (c == '(') {
break;
} else {
sb.append(c);
}
}
}else if (Character.isDigit(input.charAt(i))){
//如果是数字
sb.append(input.charAt(i));
sb.append("&");
}else {
return new StringBuilder("But the expression contains unrecognizable characters");
}
}
for (int i = 0; i <= opStack.size(); i++) {
sb.append(opStack.pop());
}
return sb;
}
int GetRes(StringBuilder s){
int res;
int i = 0;
while(true)
{
if (i > s.length()-1)
{
break;
}
while (s.charAt(i)=='&')//去除无效的空格
++i;
if(s.charAt(i)>='0'&&s.charAt(i)<='9')
{
int num=0;
while (s.charAt(i) >= '0'&&s.charAt(i) <= '9')
num = num*10 + s.charAt(i++)-'0';
container.push(num);
continue;
}
else
{
int b = container.peek();
container.pop();
int a = container.peek();
container.pop();
int c = 0;
if(s.charAt(i)=='+')
c = a+b;
else if(s.charAt(i)=='-')
c = a-b;
else if(s.charAt(i)=='*')
c = a*b;
else if(s.charAt(i)=='/')
c = a/b;
container.push(c);
//container.list();
}
++i;
}
return container.peek();
}
public void execute(String str,JTextArea jta) {
RpnMain rpnMain = new RpnMain();
String input = str;
if (rpnMain.isMatch(input)) {
jta.append("The expression's brackets are matchedn");
// 获取逆波兰式
jta.append("The RPN: "+rpnMain.getRpn(input));
jta.append(" = "+rpnMain.GetRes(sb));
} else {
jta.append("Error: The expression's brackets are not matched! Enter 'q' to exit");
}
}
}
(2)ArrayStack类
package Lab;
public class ArrayStack{
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
public boolean isFull() {
return top == this.maxSize-1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int ele) {
if(isFull()) {
return;
}
top++;
stack[top] = ele;
}
public int pop() {
if(isEmpty()) {
throw new RuntimeException("栈为空!");
}
int value = stack[top];
top--;
return value;
}
public int peek() {
if(isEmpty()) {
throw new RuntimeException("栈为空!");
}
return stack[top];
}
}
结尾
这些代码可能存在一些问题,欢迎指出,我会用心更改的。
import javax.swing.JTextArea;
public class LexicalAnalyzer {
static String[] rwtab=new String[]{"main","if","then","while","do","static",
"int","double","struct","break","else",
"long","switch","case","typedef","char",
"return","const","float","short","continue",
"for","void","sizeof"}; //定义的24个关键字,种别码从1开始
static String storage=""; //存储源程序字符串
static StringBuilder token=new StringBuilder(""); //存储单词自身组成的字符串
private char lastchar; //单个读取字符
private int index=0; //单行字符串脚标
private int syn; //种别码
private int row=1;
//分析器
void analyzer(){
token.delete(0, token.length()); //置空token对象,清除
lastchar=storage.charAt(index); //索引指向第0位
if(((lastchar>='a'&&lastchar<='z')||(lastchar>='A'&&lastchar<='Z'))&&index='0'&&lastchar<='9')||(lastchar>='a'&&lastchar<='z')||(lastchar>='A'&&lastchar<='Z'))&&index='0'&&lastchar<='9')||(lastchar>='a'&&lastchar<='z')||(lastchar>='A'&&lastchar<='Z')) {
token.append(lastchar);
}else {
index--;
}
}
syn=2; //默认为识别出的字符串为自定义的标识符,种别码为2
String s=token.toString();
for(int i=0; i='0'&&lastchar<='9')&&index='0'&&lastchar<='9'||lastchar=='.')&&index='0'&&lastchar<='9')||lastchar=='.') {
token.append(lastchar);
}else {
index--;
}
}
syn=3; //整数的种别码为3
}else if(index'){
token.append(lastchar);
index++;
}
}
break;
case '>':
token.append(lastchar);
syn=4;
if(index
实验二:递归下降分析
实验目的
根据某一文法编制调试递归下降分析程序,以便对任意输入的符号串进行分析。本次实验的目的主要是加深对递归下降分析法的理解。
实验截图
实验代码
package Lab;
import java.util.Scanner;
import javax.swing.JTextArea;
public class RecursiveAnalyzer {
static String str = "";
static char sym;
static char t[];
static int j=0;
static JTextArea jta;
public void execute(String str,JTextArea jta) {
this.jta = jta;
this.str=str;
jta.append("编制人: 姓名, 学号, 班级n");
t = str.toCharArray();
sym=t[j++];
p();
E();
//文法
if(sym=='#') {
jta.append(str+" is illegal string!");
}else {
error();
}
}
static void error() {
jta.append(str+" is valid string!n");
return;
}
static void p() {
System.out.print(sym);
}
static void E() {
if(sym == 'e') {
sym=t[j++];
p();
B();}
else if(sym == 'a') {
sym=t[j++];
p();
A();
}
else
error();
}
static void A() {
if(sym=='a') {
sym=t[j++];
p();
}
else if(sym == 'b') {
sym=t[j++];
p();
A();
}
else if(sym=='c') {
sym=t[j++];
p();
B();
}
else
error();
}
static void B() {
if(sym=='d') {
sym=t[j++];
p();
E();
if(sym=='d') {
sym=t[j++];
p();
}
else error();
}
else if(sym=='a') {
sym=t[j++];
p();
C();
}
else
error();
}
static void C() {
if(sym=='e') {
sym=t[j++];
p();
}
else if(sym=='d') {
sym=t[j++];
p();
C();
}
else
error();
}
}
实验三:LL1
实验目的
根据某一文法编制调试LL(1)分析程序,以便对任意输入的符号串进行分析。本次实验的目的主要是加深对预测分析LL(1)分析法的理解。
(1)E->TG
(2)G->+TG|-TG
(3)G->ε
(4)T->FS
(5)S->*FS|/FS
(6)S->ε
(7)F->(E)
(8)F->i
实验截图
实验代码
package Lab;
import java.io.*;
import javax.swing.JTextArea;
public class LL1 {
String Vn[] = {"E", "G", "T", "S", "F"};
String Vt[] = {"i", "+", "-", "*", "/", "(", ")", "#"};
String P[][] = new String[5][8];
String fenxi[] ;
int count = 1;
int count1 = 1;
int count2 = 0, count3 = 0;
boolean flag;
static String str;
static JTextArea jta;
public void setCount(int count, int count1, int count2, int count3){
this.count = count;
this.count1 = count1;
this.count2 = count2;
this.count3 = count3;
flag = false;
}
public void setFenxi() {
fenxi = new String[20];
fenxi[0] = "#";
fenxi[1] = "E";
}
public void setP() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 8; j++)
{
P[i][j] = "null";
}
}
P[0][0] = "->TG";
P[0][5] = "->TG";
P[1][1] = "->+TG";
P[1][2] = "->-TG";
P[1][6] = "->ε";
P[1][7] = "->ε";
P[2][0] = "->FS";
P[2][5] = "->FS";
P[3][1] = "->ε";
P[3][2] = "->ε";
P[3][3] = "->*FS";
P[3][4] = "->/FS";
P[3][6] = "->ε";
P[3][7] = "->ε";
P[4][0] = "->i";
P[4][5] = "->i";
}
public boolean judge() {
//jta.append("judge");
String inputChar = str.substring(0, 1);
boolean flage = false;
if (count1 >= 0) {
for (int i=0; i<6; i++) {
if (fenxi[count1].equals(Vt[i])) {
flage = true;
break;
}
}
}
if (flage) {
if (fenxi[count1].equals(inputChar)) {
if (fenxi[count1].equals("#")&&str.length()==1){
String fenxizhan = "";
for (int i=0; i<=P.length; i++) {
if (fenxi[i] == null) {
break;
} else {
fenxizhan = fenxizhan + fenxi[i];
}
}
jta.append(" " + count);
String countToString = Integer.toString(count);
int farWay = 14 - countToString.length();
for (int k=0; k 1) {
str = str.substring(1, str.length());
} else {
inputChar = str;
}
count++;
judge();
}
}else {
jta.append(" 分析到第" + count + "步时出错!n");
flag = false;
return false;
}
} else {
boolean fla = false;
for (int i=0; i<8; i++) {
if (inputChar.equals(Vt[i])) {
fla = true;
count2 = i;
break;
}
}
if(!fla){
jta.append(" 分析到第" + count + "步时出错!n");
flag = false;
return false;
}
for (int i=0; i<5; i++) {
if (fenxi[count1].equals(Vn[i])) {
count3 = i;
break;
}
}
if (P[count3][count2] != "null") {
String p = P[count3][count2];
String s1 = p.substring(2, p.length());
if (s1.equals("ε")) {
String fenxizhan = "";
for (int i=0; i<=P.length; i++) {
if (fenxi[i] == null) {
break;
} else {
fenxizhan = fenxizhan + fenxi[i];
}
}
jta.append(" " + count);
String countToString = Integer.toString(count);
int farWay = 14 - countToString.length();
for (int k=0; k
实验四:波兰式与四元式及计算(只能进行个位数的计算,两位及以上的有问题,做不出来。)
实验目的
将非后缀式用来表示的算术表达式转换为用逆波兰式来表示的算术表达式,并计算用逆波兰式来表示的算术表达式的值。
实验截图
实验代码
(1)RpnMain类
package Lab;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
import javax.swing.JTextArea;
public class RpnMain {
static StringBuilder sb;
ArrayStack container = new ArrayStack(20);
public boolean isMatch(String s) {
//括号符号栈
Stack charStack = new Stack<>();
//将表达式的字符串转换成数组
char[] charArray = s.toCharArray();
//遍历数组
for (char aChar : charArray) {
if (aChar == '(') {
charStack.push(aChar);
} else if (aChar == ')') {
//如果是 ) , 且栈为空则返回 false
if (charStack.isEmpty()) {
return false;
} else {
if (charStack.peek() == '(') {
charStack.pop();
}
}
}
}
//走到这里, 栈为空则表达式正确
return charStack.empty();
}
public boolean isOperator(char charAt) {
return charAt == '+' || charAt == '-' || charAt == '*' || charAt == '/';
}
public StringBuilder getRpn(String input) {
sb = new StringBuilder();
//运算符栈
Stack opStack = new Stack();
Map opMap = new HashMap(5);
opMap.put('(', 0);
opMap.put('+', 1);
opMap.put('-', 1);
opMap.put('*', 2);
opMap.put('/', 2);
//处理字符串
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(') {
opStack.push('(');
} else if (new RpnMain().isOperator(input.charAt(i))) {
//如果是运算符
char curOp = input.charAt(i);
if (opStack.isEmpty()) {
opStack.push(curOp);
} else if (opMap.get(curOp) > opMap.get(opStack.peek())) {
opStack.push(curOp);
} else {
for (int j = 0; j <= opStack.size(); j++) {
//弹出栈内第一个元素
char ch = opStack.pop();
sb.append(ch);
if (opStack.isEmpty()) {
opStack.push(curOp);
break;
} else if (opMap.get(curOp) > opMap.get(opStack.peek())) {
opStack.push(curOp);
break;
}
}
}
} else if (input.charAt(i) == ')') {
for (int j = 0; j < opStack.size(); j++) {
char c = opStack.pop();
if (c == '(') {
break;
} else {
sb.append(c);
}
}
}else if (Character.isDigit(input.charAt(i))){
//如果是数字
sb.append(input.charAt(i));
sb.append("&");
}else {
return new StringBuilder("But the expression contains unrecognizable characters");
}
}
for (int i = 0; i <= opStack.size(); i++) {
sb.append(opStack.pop());
}
return sb;
}
int GetRes(StringBuilder s){
int res;
int i = 0;
while(true)
{
if (i > s.length()-1)
{
break;
}
while (s.charAt(i)=='&')//去除无效的空格
++i;
if(s.charAt(i)>='0'&&s.charAt(i)<='9')
{
int num=0;
while (s.charAt(i) >= '0'&&s.charAt(i) <= '9')
num = num*10 + s.charAt(i++)-'0';
container.push(num);
continue;
}
else
{
int b = container.peek();
container.pop();
int a = container.peek();
container.pop();
int c = 0;
if(s.charAt(i)=='+')
c = a+b;
else if(s.charAt(i)=='-')
c = a-b;
else if(s.charAt(i)=='*')
c = a*b;
else if(s.charAt(i)=='/')
c = a/b;
container.push(c);
//container.list();
}
++i;
}
return container.peek();
}
public void execute(String str,JTextArea jta) {
RpnMain rpnMain = new RpnMain();
String input = str;
if (rpnMain.isMatch(input)) {
jta.append("The expression's brackets are matchedn");
// 获取逆波兰式
jta.append("The RPN: "+rpnMain.getRpn(input));
jta.append(" = "+rpnMain.GetRes(sb));
} else {
jta.append("Error: The expression's brackets are not matched! Enter 'q' to exit");
}
}
}
(2)ArrayStack类
package Lab;
public class ArrayStack{
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
public boolean isFull() {
return top == this.maxSize-1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int ele) {
if(isFull()) {
return;
}
top++;
stack[top] = ele;
}
public int pop() {
if(isEmpty()) {
throw new RuntimeException("栈为空!");
}
int value = stack[top];
top--;
return value;
}
public int peek() {
if(isEmpty()) {
throw new RuntimeException("栈为空!");
}
return stack[top];
}
}
结尾
这些代码可能存在一些问题,欢迎指出,我会用心更改的。



