2013-11-26 59 views
1

錯誤: 異常在線程 「主」 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:5 在java.lang.String.charAt(未知來源) 在Convert.main(Convert.java:16)這個錯誤和我的代碼之間有什麼錯?

公共類轉換{

public static void main(String[] args) { 
    int i=0; 
    int j=0; 
    char p[] = new char[10]; // postfix 
    Stk s = new Stk();   // stack 
    String str = new String(); // infix 

    str = JOptionPane.showInputDialog("Please enter a infix expression:"); 

    while(str.length() >= 1) 
    { 
     if(operand (str.charAt(i))) 
      p[j++] = str.charAt(i); 

     else if (!operand(str.charAt(i))) 
     { 
      while(!s.isEmpty() && precedence(str.charAt(i)) <= precedence(s.stack[s.top])) 
       p[j++] = s.pop(); 
      s.push(str.charAt(i)); 
     } 

     i++; 
    } 

    while (!s.isEmpty()) 
    { 
     p[j++] = s.pop(); 
    } 

    String P = new String(p); 
    JOptionPane.showMessageDialog(null , "Postfix expression is : " + P); 
} 

public static boolean operand(char b) 
{ 
    if (b!='+' || b!='-' || b!='*' || b!='/') 
     return true; 
    else 
     return false; 
} 

public static int precedence(char c) 
{ 
    int x=0; 

    switch(c) 
    { 
     case '*': 
     case '/': 
     x=2; 
     break; 

     case '+': 
     case '-': 
     x=1; 
     break; 
    }    
    return x; 

}
}

回答

0

本聲明引起的問題:

while(str.length() >= 1) 

將其更改爲:

while(i<str.length()) 

原因:你總是使用的,而條件不再成立時,如果用戶輸入5字母串,然後str.length()是5,所以雖然條件while(5>=1)是總是如此,所以控制進入循環內部並且每次迭代i從0,1,2,3,4然後5增加。當i是5時,拋出異常,因爲字符串僅具有0,1,2,3, 4個字符..

編輯:
修復了中的邏輯方法:

public static boolean operand(char b) { 
    if (b == '+' || b == '-' || b == '*' || b == '/') 
     return false; 
    else 
     return true; 
} 
+0

錯誤已更正,但輸出錯誤!例如,當我輸入「a + b * c」時,我會收到相同的字符串「a + b * c」,並且它會將表達式從中綴轉換爲後綴!請幫助我.. – endorbor

+0

編輯了答案,問題出在你的'operand'方法中。 –

+0

非常感謝您的幫助...... – endorbor