package Test;
import java.util.Stack;
public class Expression
{
public Expression(String src)
{
// TODO Auto-generated constructor stub
this.src = src;
des = new char[MAX_LENGTH];
}
//将输入的中缀表达式转换成后缀表达式
public void isLegal(){
if(src.charAt(0)=='+'||src.charAt(0)=='*'){
System.out.println(src+" "+"非法表达式");
System.exit(0);
}
for(int i=1;i<src.length();++i){
if(src.charAt(i)<='Z'&&src.charAt(i)>='A'){
if(src.charAt(i-1)<='Z'&&src.charAt(i-1)>='A'||src.charAt(i+1)<='Z'&&src.charAt(i+1)>='A'){
System.out.println(src+" "+"非法表达式");
System.exit(0);
}
else continue;
}
else if(src.charAt(i)=='+'||src.charAt(i)=='*'){
if(((src.charAt(i-1)<='Z'&&src.charAt(i-1)>='A')||src.charAt(i-1)==')')&&((src.charAt(i+1)<='Z'&&src.charAt(i+1)>='A')||src.charAt(i+1)=='('||src.charAt(i+1)=='!'))
continue;
else{
System.out.println(src+" "+"非法表达式");
System.exit(0);
}
}
}
}
public int getRank(char c)
{
switch (c)
{
case '!':
return 4;
case '*':
return 3;
case '+':
return 2;
case '(':
return 1;
case ')':
return 1;
default:
return -1;
}
}
public void translate()
{
Stack<Character> set = new Stack<Character>();//运算的集合
Stack<Character> opr = new Stack<Character>();//运算的操作符
int count = 0;
for(int i=0;i <src.length();i++)
{
if(src.charAt(i) <='Z' && src.charAt(i)>= 'A') //是字母的时候
{
des[count++] = src.charAt(i);
}
else if(src.charAt(i) == '(')//是左括号
{
opr.push('(');
}
else if(src.charAt(i) == ')')//是右括号
{
while(!opr.empty()&&opr.peek() != '(')
{
des[count++]= opr.pop();
}
if(opr.empty()){
System.out.println(src+" "+"右括号不匹配");
System.exit(0);
}
else
opr.pop();
}
else //是 + * !时//是普通操作符号的时候
{
if(opr.empty())
{
opr.push(src.charAt(i));
}
else
{
if( getRank(src.charAt(i)) >getRank(opr.peek()))
{
opr.push(src.charAt(i));
}
else
{
while(!opr.empty())
{
des[count++]= opr.pop();
}
opr.push(src.charAt(i));