2015-07-11 30 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

刚刚做了,再次感谢! –

相关问题