我疯了......我非常接近让我的代码以我想要的方式工作,我无法理解。我正在尝试为ex解决一个后缀方程。 3 2 +,这等于5.当我举例说 主方法中的“3 2 +”它工作正常但是一旦我输入第三个数字,如“3 2 + 2 *”(等于10),我得到一个arrayoutofboundserror,回到number2 = s.pop(),因为你将请参阅下面的代码。任何帮助是极大的赞赏。
下面是后缀meethod:
public int PostfixEvaluate(String e){
int number1;
int number2;
int result=0;
String[] tokens = e.split(" ");
for(int j = 0; j < tokens.length; j++){
String token = tokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
String Operator = tokens[j];
number1 = s.pop();
number2 = s.pop();
if (Operator.equals("/")){
result = number1 / number2;}
else if(Operator.equals("*")){
result = number1 * number2;}
else if(Operator.equals("+")){
result = number1 + number2;}
else if(Operator.equals("-")){
result = number1 - number2;}
else System.out.println("Illeagal symbol");
}
s.push(result);
s.pop();
}
//s.pop();
System.out.println("Postfix Evauation = " + result);
return result;
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
//String y = new String("((z * j)/(b * 8) ^2");
String x = new String("2 2 2 * +");
TestingClass clas = new TestingClass(st);
//clas.test(y);
clas.PostfixEvaluate(x);
}
}
答案 0 :(得分:3)
/**
* Evaluate postfix arithmetic expression
*
* @example "1 12 23 + * 4 5 / -" => 34.2
* @author Yong Su
*/
import java.util.Stack;
class PostfixEvaluation {
public static void main(String[] args) {
String postfix = "1 12 23 + * 4 5 / -";
Double value = evaluate(postfix);
System.out.println(value);
}
/**
* Evaluate postfix expression
*
* @param postfix The postfix expression
*/
public static Double evaluate(String postfix) {
// Use a stack to track all the numbers and temporary results
Stack<Double> s = new Stack<Double>();
// Convert expression to char array
char[] chars = postfix.toCharArray();
// Cache the length of expression
int N = chars.length;
for (int i = 0; i < N; i++) {
char ch = chars[i];
if (isOperator(ch)) {
// Operator, simply pop out two numbers from stack and perfom operation
// Notice the order of operands
switch (ch) {
case '+': s.push(s.pop() + s.pop()); break;
case '*': s.push(s.pop() * s.pop()); break;
case '-': s.push(-s.pop() + s.pop()); break;
case '/': s.push(1 / s.pop() * s.pop()); break;
}
} else if(Character.isDigit(ch)) {
// Number, push to the stack
s.push(0.0);
while (Character.isDigit(chars[i]))
s.push(10.0 * s.pop() + (chars[i++] - '0'));
}
}
// The final result should be located in the bottom of stack
// Otherwise return 0.0
if (!s.isEmpty())
return s.pop();
else
return 0.0;
}
/**
* Check if the character is an operator
*/
private static boolean isOperator(char ch) {
return ch == '*' || ch == '/' || ch == '+' || ch == '-';
}
}
答案 1 :(得分:3)
number1赋值应该在number2赋值之后。请记住,s.pop()将删除并返回顶部的数字。
number2 = s.pop();
number1 = s.pop();
答案 2 :(得分:1)
推后会立即弹出吗?
s.push(result);
s.pop();
答案 3 :(得分:1)
此解决方案中存在另一个逻辑错误。你需要这样做:
number2 = s.pop();
number1 = s.pop();
如果您有32/
,那么您的解决方案将无效,因为您会将其评估为2/3
。