编译原理算符优先矩阵
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package Test4;
import java.io.*;
import java.util.Stack;
public class Test4_1 {
private static int x;
private static char ch;
private static char c;
static int[][] a={{1,1,-1,-1,-1,1,1},{1,1,-1,-1,-1,1,1},{1,1,1,1,-1,1,1},{1,1,1,1,-1,1,1},{-1,-1,-1,-1,-1,2,0},{1,1,1 ,1,1,1,0},{-1,-1,-1,-1,-1,2,0}};
static char b[]={'+','-','*','/','(',')','#'};
public static void stackPrint(String s)
{
int m = 0;
Stack<Character> op1=new Stack<Character>();
Stack<Character> op2=new Stack<Character>();
op1.empty();
op2.push('#');
while(m<s.length())
{
ch=s.charAt(m);
c=op2.peek().toString().charAt(0);
if(ch=='+') x=0;
else if(ch=='-')x=1;
else if(ch=='*')x=2;
else if(ch=='/')x=3;
else if(ch=='(')x=4;
else if(ch==')')x=5;
else if(ch=='#')x=6;
else if(ch>='0'||ch<='9')x=7;
else
{System.out.println("出错!");return;}
switch(x)
{
case 0:
{
if(c=='*'||c=='/'||c=='('||c=='#')
{op2.push(ch);m++; break;}
else if(c=='+'||c=='-'||c==')')
{
op2.pop();op1.pop();op1.pop();m++;break;
}
}
case 1:
{
if(c=='*'||c=='/'||c=='(')
{op2.push(ch);m++;}
else if(c=='+'||c=='-'||c==')'||c=='#')
{op2.pop();op1.pop();op1.pop();m++;}
break;
}
case 2:
{
if(c=='(')
{op2.push(ch);m++;}
else if(c=='*'||c=='/'||c==')'||c=='+'||c=='-'||c=='#')
{op1.pop();op1.pop();op1.push('2');m++;}
break;
}
case 3:
{
if(c=='(')
{op2.push(ch);m++;break;}
else if(c=='*'||c=='/'||c==')'||c=='+'||c=='-'||c=='#')
{
op2.pop();
op1.pop();
op1.pop();
op1.push('2');
m++;
break;
}
}
case 4:
{
if(c=='*'||c=='/'||c=='('||c=='+'||c=='-')
{op2.push(ch);m++;}
else if(c==')')
{
op2.pop();
op1.pop();
op1.pop();
op1.push('2');
op2.pop();
m++;
}
break;
}
case 5:
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c==')'||c=='('||c=='#')
{op2.pop();op1.pop();op1.pop();op2.pop();op1.push('2');m++;}
break;
}
case 6:
{
if(c=='#')
{System.out.println("正确!");m++;break;}
else if(c=='+'||c=='-'||c=='*'||c=='/')
{op2.pop();op1.pop();op1.pop();op1.push('2');break;}
else
{System.out.println("出错!");return;}
}
case 7:
{
op1.push(ch);
m++;
break;
}
}
}
}
public static void main(String args[]) throws IOException
{
System.out.println("算符优先矩阵:");
System.out.println("\t+\t-\t*\t/\t(\t)\t#");
for(int i=0;i<7;i++)
{
System.out.print(b[i]+"\t");
for(int j=0;j<7;j++)
{
if(a[i][j]==1)
System.out.print(">"+"\t");
if(a[i][j]==-1)
System.out.print("<"+"\t");
if(a[i][j]==0)
System.out.print(""+"\t");
if(a[i][j]==2)
System.out.print("="+"\t");
}
System.out.println();
}