JAVA-Why/Where 我在尝试将中缀转换为 post 修复表达式时是否收到数组索引超出范围的错误?
JAVA-Why/Where am I getting an Array Index out of bound error while trying to covert an infix to post fix expression?
这是我将中缀表达式转换为后缀表达式的代码。问题出在转换方法上。我在第 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 作为向量的索引。我猜你的肉是什么:
st.push(e.charAt(i));
这是我将中缀表达式转换为后缀表达式的代码。问题出在转换方法上。我在第 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 作为向量的索引。我猜你的肉是什么:
st.push(e.charAt(i));