这是我将中缀表达式转换为后缀表达式的代码。问题出在转换方法上。我在第 21 行收到错误。
Error-ab+ Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 >= 0
at java.util.Vector.elementAt(Unknown Source)
at infixpostfix.conversion(infixpostfix.java:22)
at infixpostfix.main(infixpostfix.java:77)
当前输入。
我认为出现此错误是因为我正在尝试访问 i
当它超过我的字符串长度时。但是当我的 i 值由 for 循环控制时怎么可能呢?
Code:-
import java.util.Stack;
public class infixpostfix {
Stack<Character> st = new Stack<Character>();
void conversion(String e){
for(int i = 0 ; i < e.length() ; i++){
if(isOp(e.charAt(i)) ){
if(st.isEmpty()){
st.push(e.charAt(i));
}
else{
while(!st.isEmpty() && checkPrec(st.peek())<=checkPrec(e.charAt(i))){
System.out.println(st.pop());
}
st.push(st.elementAt(i));
}
}
else{
System.out.print(e.charAt(i));
}
}
while(!st.isEmpty()){
System.out.print(st.pop());
}
}
int checkPrec(char o){
switch(o){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
boolean isOp(char c){
if(c=='+' || c=='-' || c=='/' || c=='*'){
return true;
}
else{
return false;
}
}
public static void main(String args[]){
infixpostfix obj = new infixpostfix();
obj.conversion("a+b-c/d*f");
}
}
最佳答案
据我了解,i
表示字符串中的索引。然而,这里:
st.push(st.elementAt(i));
您正在使用 at 作为 vector 的索引。我猜你的肉是什么:
st.push(e.charAt(i));
关于JAVA-为什么/在尝试将中缀表达式转换为后缀表达式时,我在哪里收到数组索引越界错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322979/