问题描述
- 有谁懂算符优先文法语法分析吗
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Scanner;
import java.util.Stack;
public class compiler3 {
private static char O_Table[][]={
{'>','>','<','<','<','>','<','>'},// +
{'>','>','<','<','<','>','<','>'},// -
{'>','>','>','>','<','>','<','>'},// *
{'>','>','<','<','<','>','<','>'},// /
{'<','<','<','<','<','=','<','-'},// (
{'>','>','>','>','-','>','-','>'},// )
{'>','>','>','>','-','>',' ','>'},// i
{'<','>','<','<','<','-','<','='}// #
};
private static char Vt[]={'+','-','*','/','(',')','0','1','2','3','4','5','6','7','8','9','#'};
static char ch;
// private static char[] Vn={'E'};
private static int judgePriority(char ch){
int priority=0;
switch (ch) {
case '+':
priority=0;
break;
case'-':
priority=1;
break;
case'*':
priority=2;
break;
case'/':
priority=3;
break;
case'(':
priority=4;
break;
case')':
priority=5;
break;
case'i':
priority=6;
break;
case'#':
priority=7;
break;default: break; } return priority; } public static char getPriority(char m,char n) { return O_Table[judgePriority(m)][judgePriority(n)]; }
// public static char getCurrent(String str,int current) {
// return str.charAt(current);
//// }
public static boolean isVt(char ch) {
int i;
for(i=0;i<Vt.length;i++){
if(Vt[i]==ch)
return true;} return false; }
// public static boolean isOperator(char ch) {
// if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#')
// return true;
// return false;
// }
public static boolean isDigit(char ch) {
if((ch>='0')&&(ch<='9'))
return true;
return false;
}
public static void Analysis(String in) {
int i,r = 0;
String a,b;
String str="";
Character op;
Stack OPTR =new Stack();
Stack OPND = new Stack();
OPTR.push('#');
for(i=0;i<in.length();i++){
ch=in.charAt(i);
// System.out.println(ch);
if(isDigit(ch)){
str=str+ch;i++;
}else {
// System.out.println(ch);
OPND.push(str);
System.out.println(OPND);
// OPTR.push(ch);
if(getPriority(OPTR.lastElement(), in.charAt(i))=='>'){
a=OPND.pop();
b=OPND.pop();
op=OPTR.pop();
System.out.println(a+b+op);
switch (op) {
case '+':
r=Integer.parseInt(a)+Integer.parseInt(b);
break;
case '-':
r=Integer.parseInt(a)-Integer.parseInt(b);
break;
case '*':
r=Integer.parseInt(a)-Integer.parseInt(b);
break;
case '/':
r=Integer.parseInt(a)-Integer.parseInt(b);
break;
default:
break;}
String str1=Integer.toString(r);
OPND.push(str1);
}
else if (getPriority(OPTR.lastElement(), ch)=='<') {
OPTR.push(ch);} else if (getPriority(OPTR.lastElement(), ch)=='=') { OPTR.pop(); OPTR.pop(); } else if (OPTR.empty()) { System.out.println("式子正确"); } else { System.out.println("分析出错"); } } }
}
public static void main(String[] args) throws IOException {
System.out.println("请输入以“#”结束的表达式:"); //自下而上的语法分析方法-算符优先文法处理
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String in = br.readLine();
Analysis(in);}
}
文法是E-E+E|E*E|E-E| E/E |(E)|i 找了好久 , 不知道哪里出现了逻辑错误 ,求帮忙看看万分感谢