我正在写一个后缀解决方案。我不知道为什么它不起作用,并且我一直在输出中得到 -1。有人可以帮忙吗?我将包括跑步者和跑步者以及实际的后缀类。
import java.util.Stack;
import java.util.Scanner;
import static java.lang.System.*;
public class PostFixRunner
{
public static void main ( String[] args )
{
PostFix test = new PostFix("2 7 + 1 2 + +");
System.out.println(test.solve());
test.setExpression("1 2 3 4 + + +");
System.out.println(test.solve());
test.setExpression("9 3 * 8 / 4 +");
System.out.println(test.solve());
test.setExpression("3 3 + 7 * 9 2 / +");
System.out.println(test.solve());
test.setExpression("9 3 / 2 * 7 9 * + 4 -");
System.out.println(test.solve());
test.setExpression("5 5 + 2 * 4 / 9 +");
System.out.println(test.solve());
}
}
和这个...
import java.util.Stack;
import java.util.Scanner;
import static java.lang.System.*;
public class PostFix
{
private Stack<Integer> stack;
private String theExp;
public PostFix()
{
}
public PostFix(String exp)
{
theExp = exp;
stack = new Stack<Integer>();
}
public void setExpression(String exp)
{
theExp= exp;
while (!stack.isEmpty()){
stack.pop();
}
}
public int calc(int two, int one, char current)
{
int output;
switch(current){
case '*':
output=one*two;
break;
case '/':
output=one/two;
break;
case '+':
output=one+two;
break;
case '-':
output=one-two;
break;
default:
output=0;
}
return output;
}
public int solve()
{
for (int i=0; i<theExp.length(); i++){
char current = theExp.charAt(i);
int currentInt = (int)Character.digit(current, 10);
if (current!='*'||current!='/'||current!='+'||current!='-')
stack.push(currentInt);
else
stack.push(calc(stack.pop(), stack.pop(), current));
}
return stack.pop();
}
public String toString(){
return stack.toString();
}
}