I'm trying to make an RPN calculator. I have done the conversion from infix to postfix, now I want to evaluate the converted expression. When I enter any expression I get error
String index out of range: 1.
Here's my code with what I'm supposed to do in the program:
static int eval(String postfix) {
int result = 0;
String temp2 = "";
int num1, num2, OPS;
char operator;
String delete = "";
for (int i = 0; i < postfix.length(); i++) {
char M = postfix.charAt(i);
// if v_i is an operand: Push v_i to tmp2.
if (Character.isDigit(postfix.charAt(i))) {
temp2 = M + temp2;
}
/*
* if v_i is an operator: Apply v_i to the top two elements of tmp2.
* Replace these by the result in tmp2.
*/
if (postfix.charAt(i) == '+' || postfix.charAt(i) == '-' || postfix.charAt(i) == '*'
|| postfix.charAt(i) == '/') {
temp2 = M + temp2.substring(2);
}
while (postfix.charAt(0) != '0') {
num1 = Character.getNumericValue(temp2.charAt(temp2.length()-1));
delete = delete.substring(0,i);
operator = postfix.charAt(i);
num2 = Character.getNumericValue(temp2.charAt(temp2.length()+i));
//Integer.parseInt(postfix.substring(0,i));
result = num1 + num2;
result = num1 - num2;
result = num1 * num2;
result = num1 / num2;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
}
if (temp2.length() != 0) {
temp2 = result + temp2;
}
}
return result;
}
I get the error in this part:
while (postfix.charAt(0) != '0') {
num1 = Character.getNumericValue(temp2.charAt(temp2.length()-1));
delete = delete.substring(0,i);
operator = postfix.charAt(i);
num2 = Character.getNumericValue(temp2.charAt(temp2.length()+i));
//Integer.parseInt(postfix.substring(0,i));
As you can see, I have tried some different string manipulation but they're all incorrect.
My supervisor said something about reading the string from backwards or the last string or something, But I never understood what they meant. Thanks for any help in advance
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…