package postfix;
import java.io.IOException;
import java.lang.StringBuilder;
/**
* 预测分析类
* 简单表达式的翻译器
* @author denglt
*
*/
class Parser {
/**
* lookahead : 向前看符号
*/
static int lookahead;
/**
* 用来记录输入的串中字符的位置,第一个为 1
*/
static int index;
/**
* 设置一个字符串缓冲区来保存运行时所发现的错误位置及其原因
*/
static StringBuilder errorbuffer ;
/**
* 构造函数
* 初始化 —— index , lookahead , 字符串缓冲区
*/
public Parser(){
errorbuffer = new StringBuilder("");
try {
lookahead = System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
if((char)lookahead == '\r'){
errorbuffer.append("错误类型:输入表达式为空.");
}
index = 1;
}
/**
* 翻译表达式
*/
void expr() {
/**
* 数字分析器
*/
if( ! term()){
errorbuffer.append("错误类型:缺失左运算量—表达式不以数字开头.\n");
return ;
}
/**
* 采用循环方法
*/
while(true){
/**
* 如果 lookahead 为 + 号,则进入加法产生式
*/
if ((char)lookahead == '+') {
if( ! match('+')){
errorbuffer.append("错误类型:缺失右运算量——第 "+index+" 个字符('+')后缺失运算量.\n");
break;
}
if( ! term()){
errorbuffer.append("错误类型:缺失右运算量——最后一个数字的运算符('+')后缺失运算量.\n");
break;
}
System.out.print('+');
/**
* 如果为 - 号,则进入 减法产生式
*/
} else if ((char)lookahead == '-') {
if( ! match('-')){
errorbuffer.append("错误类型:缺失右运算量——第 "+index+" 个字符('-')后缺失运算量.\n");
break;
}
if( ! term()){
errorbuffer.append("错误类型:缺失右运算量——最后一个数字的运算符('-')后缺失运算量.\n");
break;
}
System.out.print('-');
} else {
/**
* 否则发生异常先判断是否已经到了行尾
* 是则退出程序
*/
if((char)lookahead == '\r'){
break ;
}
/**
* 若不是,则将错误信息压入到 错误缓冲区中,程序继续向下运行
*/
if(Character.isDigit((char)lookahead)){
errorbuffer.append("错误类型:缺失运算符—第 "+index+" 个数字前缺失一个运算符.\n");
}else {
errorbuffer.append("错误类型:缺失运算符—第 "+index+" 个字符出错,它不是一个运算符.\n");
}
/**
* 然后向前看符合再往前一步
*/
try {
lookahead = System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
/**
* 若已经到了行尾,则退出程序
*/
if((char)lookahead == '\r') {
break ;
}
index ++ ;
}
}
}
/**
* 翻译数字
*/
boolean term(){
/**
* 若读取的是数字,则输出并调用 match() 函数
*/
while(true){
if (Character.isDigit((char)lookahead)) {
System.out.print((char)lookahead);
match(lookahead);
break;
} else {
/**
* 否则,判断是否到了行尾,是则退出函数
*/
if((char)lookahead == '\r'){
return false;
}else{
/**
* 若不是,则表示出现了错误,将错误信息压入缓冲区,程序继续向下运行
*/
errorbuffer.append("错误类型:缺失运算量——第 "+index+" 个字符出错,它不是一个数字.\n");
/**
* 向前看符合继续往前一步
*/
try {
lookahead = System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
/**
* 若已经到表达式尾部,则退出
*/
if((char)lookahead == '\r'){
return false;
}else{
/**
* 否则,将位置加 一
* 继续进行数字分析
*/
index ++ ;
continue;
}
}
}
}
return true;
}
/**
* 匹配函数
* 若匹配则向前看符合往前一步
* @param t
*/
boolean match(int t) {
if (lookahead == t){
/**
* 匹配则继续向前读取
*/
try {
lookahead = System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
/**
* 若已经到行尾,则退出
*/
if((char)lookahead == '\r'){
return false;
}else{
/**
* 否则 index ++
*/
index ++ ;
}
}
return true ;
}
}
- 1
- 2
- 3
- 4
前往页