我正在尝试编写一种解决后缀方程的方法。对于前者
1 2 + 3 *
这将= 9
截至目前,我正在获得ArrayoutofboundsException
。我认为问题出在我的if(statement)
方法postFixEvaluation
中。
代码的第一部分是我在谈论需要帮助的地方的方法。 之后是我的其余代码。不确定你是否需要阅读。
public int PostfixEvaluate(String e) {
String Operator = "";
int number1;
int number2;
int result = 0;
char c;
number1 = 0;
number2 = 0;
for (int j = 0; j < e.length(); j++) {
c = e.charAt(j);
if (c == (Integer) (number1)) {
s.push(c);
} else {
number1 = s.pop();
number2 = s.pop();
switch (c) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
result = number1 / number2;
break;
case '%':
result = number1 % number2;
break;
}
}
}
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("10 3 + 9 *");
TestingClass clas = new TestingClass(st);
clas.test(y);
//System.out.println(stacks.test(y));
clas.PostfixEvaluate(x);
}
以下是可能相关的其余代码:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = 0;
maxLen = max;
stack = new char[maxLen];
}
public void push(int result) {
top++;
stack[top] = (char) result;
}
public int pop() {
int x;
x = stack[top];
//top = top - 1;
top--;
return x;
}
public boolean isStackEmpty() {
if (top == 0) {
System.out.println("Stack is empty " + "Equation Good");
return true;
} else
System.out.println("Equation is No good");
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for (int j = top; j > -1; j--) {
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for (int j = 0; j >= top; j++) {
System.out.println(stack[j]);
}
System.out.println(" ");
}
}
答案 0 :(得分:2)
您需要将操作结果重新推送到堆栈。然后在结束时(在表达式字符串的末尾),弹出堆栈并返回值。
// excerpted, with odd bracket indentions unchanged.
for(int j = 0; j < e.length(); j++){
c = e.charAt(j);
if (c == (Integer)(number1)) {
s.push(c); }
else {
number1 = s.pop();
number2 = s.pop();
switch(c) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
result = number1 / number2;
break;
case '%':
result = number1 % number2;
break;
}
s.push(result); // <=== push here
}
}
}
return s.pop(); // <==== pop here