2015-07-11 17 views
0

我有一個任務來創建一個程序,將中綴表達式轉換爲Postfix。我需要在操作數和運算符之間插入空格,出於某種原因我總是收到StringIndexOutOfBounds。這是我的java代碼。插入空格在操作數和運算符之間,獲取字符串出界

public class Processor { 
public String addSpace(String str){ 
    String finalstr = ""; 
    for (int i = 0; i < str.length(); i++) { 
     if(Character.isDigit(str.charAt(i))){ 
      int x = i; 
      String temp = ""; 
      do{ 
       temp+=str.charAt(x); 
       x++; 
      }while(Character.isDigit(str.charAt(x))); 
      finalstr+=(temp+" "); 
      System.out.println(temp+" added to final"); 
      i=(x-1); 
      System.out.println(x+" is x and i is "+i); 
     } 
     else if(isOperator(str.charAt(i))){ 
      finalstr+=(str.charAt(i)+" "); 
     } 
    } 
    return finalstr; 
} 

public boolean isOperator(char a){ 
    switch(a){ 
     case '+': 
     case '-': 
     case '/': 
     case '*': 
     case '(': 
     case ')': 
     return true; 
     default: return false; 
    } 
} 

回答

0

在這個循環中

do { 
    temp += str.charAt(x); 
    x++; 
} while (Character.isDigit(str.charAt(x))); 

你增加x,你需要在x位置的字符,如果沒有該字符存在的檢查。在字符串的末尾,如果字符是一個數字,那麼可以超過字符串的長度

+0

OH!非常感謝你親愛的先生。我多麼愚蠢。牙痛正在繼續,我真的無法正常工作。再次感謝你! –

+0

如果你認爲這個解決方案對你的問題是一個很好的解決方案,你可以對它進行提升並用綠色檢查將其標記爲正確答案。謝謝 –

+0

剛剛做了,再次感謝! –

相關問題