Java posfix的函数中缀无法正常工作
我有下一个将算术表达式从中缀转换为posfix的代码,例如: 2*23+6-1,在函数e中,堆栈p已经包含表达式Java posfix的函数中缀无法正常工作,java,Java,我有下一个将算术表达式从中缀转换为posfix的代码,例如: 2*23+6-1,在函数e中,堆栈p已经包含表达式 public static void e(){ String exp; Stack<String> p = new Stack<String>(); exp = posFija(p); System.out.println(" "+exp); } 下面是两个应该进行转换的函数: publ
public static void e(){
String exp;
Stack<String> p = new Stack<String>();
exp = posFija(p);
System.out.println(" "+exp);
}
下面是两个应该进行转换的函数:
public static String posFija(Stack<String> p){
String posFix = "";
Stack<String> temp = new Stack<String>();
Stack<String> s = new Stack<String>();
try
{
while(!p.isEmpty())
{
switch(pref(p.peek())){
case 1:
temp.push(p.pop());
break;
case 3:
case 4:
while(pref(temp.peek()) >= pref(p.peek()))
s.push(t.pop());
temp.push(p.pop());
break;
case 2:
while(!temp.peek().equals("("))
{
s.push(temp.pop());
}
temp.pop();
p.pop();
break;
default:
s.push(p.pop());
}
}
posFix = s.toString();
}
catch(Exception ex)
{
System.out.println("Error");
}
return posFix;
}
private static int pref(String op) {
int prf = 99;
if (op.equals("^"))
prf = 5;
if (op.equals("*") || op.equals("/"))
prf = 4;
if (op.equals("+") || op.equals("-"))
prf = 3;
if (op.equals(")"))
prf = 2;
if (op.equals("("))
prf = 1;
return prf;
}
我遇到的问题是,当开关找到表达式为2*23+6-1时,它会抛出异常,我不知道如何修复此问题,下面的代码将对其起作用。看看我对它做了什么改变
public static void e() {
String exp;
Stack<String> p = new Stack<String>();
// 2*(23+6)-1
p.push("1"); //Pushing for right to left, or you can reverse stack in posFija if you are pushing from left to right
p.push("-");
p.push(")");
p.push("6");
p.push("+");
p.push("23");
p.push("(");
p.push("*");
p.push("2");
exp = posFija(p);
System.out.println(" " + exp);
}
在pref方法中,使用if-else-if而不是if.堆栈p按什么顺序包含表达式。堆栈p的顶部包含什么,1或2?你没有在这里提到它,在这里t被声明为s.pusht.pop;您得到的是哪个异常?@Naman Gala sorry t是temp,顶部堆栈包含1,异常是ErrorIn catch block put此ex.printStackTrace;谢谢,我已经发现了问题所在,当我有一个像5+6y这样的表达式时,我必须在调用函数posfija之前加上括号5+6,我仍然有一些问题,但它现在可以工作了。根据数学,这两个表达式是不同的,即5+6y和5+6y。如果我回答了你的问题,那么请接受它。非常感谢你的帮助,我确实遵循了你建议的所有更改,现在代码工作得非常完美,顺便说一下,它只有5+6和5+6,y是一个错误的表达式,即5+6和5+6它正在工作。如果我回答了你的问题,请接受。
public static String posFija(Stack<String> p) {
String posFix = "";
Stack<String> temp = new Stack<String>();
Stack<String> s = new Stack<String>();
try {
while (!p.isEmpty()) {
switch (pref(p.peek())) {
case 1:
temp.push(p.pop());
break;
case 3:
case 4:
while (!temp.empty() && pref(temp.peek()) >= pref(p.peek())) //Empty check
s.push(temp.pop());
temp.push(p.pop());
break;
case 2:
while (!temp.peek().equals("(")) {
s.push(temp.pop());
}
temp.pop();
p.pop();
break;
default:
s.push(p.pop());
}
}
//For last element in temp
if (!temp.isEmpty() && !temp.peek().equals(")")) {
s.push(temp.pop());
}
posFix = s.toString();
//System.out.println("S: " + s);
//System.out.println("P: " + p);
//System.out.println("Temp: " + temp);
} catch (Exception ex) {
System.out.println("Error");
ex.printStackTrace();
}
return posFix;
}