2016-03-03 63 views
1

我每次尝试编译异常java.lang.StringIndexOutOfBoundsException时都出现代码问题。这是有问题的代码,我真的不知道我做错了什么。在代码中,我尝试使用一些条件拆分stringstring代表一个多项式。Java异常:java.lang.StringIndexOutOfBoundsException

int[] coef1= new int[20]; 
for(i=0;i<polinom.length()+1;i++){ 
    if(polinom.charAt(i)=='+') 
     c=polinom.charAt(i+1); 
    else{ 
     if(polinom.charAt(i)=='^'){ 
      v=Integer.parseInt(Character.toString(polinom.charAt(i+1))); 
      coef1[v]=Integer.parseInt(Character.toString(c)); 
      System.out.print(coef1[v]); 

     } 
    } 
} 
for(i=0;i<polinom.length()+1;i++){ 
    if(polinom.charAt(i)=='-') 
     c=polinom.charAt(i+1); 
    else{ 
     if(polinom.charAt(i)=='^'){ 
      v=Integer.parseInt(Character.toString(polinom.charAt(i+1))); 
      coef1[v]=-Integer.parseInt(Character.toString(c)); 
      System.out.print(coef1[v]); 

     } 
    } 
} 

唯一的例外是在这里if(polinom.charAt(i)=='+')

+3

张贴堆栈跟踪会更容易跟踪这些异常被抛出 – Ramanlfc

+0

我同意@ Ramanlfc这个错误可以相当容易地解决,如果我们知道它正在发生的线。 – basic

+3

在第二行中,您使用“for(i = 0; i f1sh

回答

4

只是所有

for(i=0;i<polinom.length()+1;i++){ 

for(i=0;i<polinom.length()-1;i++){ 

取代作为指数为基础的0和你使用polinom.charAt(i+1)i+1不应该等于(或不大于)polinom.length

或者,如果你想OT能够测试,直到字符串的最后一个字符(另处理),可以确保如果i == polinom.length() - 1,只是处理你的东西之前添加一个测试polinom.charAt(i+1)被永远不会触发:

for(i=0;i<polinom.length();i++){ // not using -1, looping to the end of the string 
    if(polinom.charAt(i)=='+' && i < polinom.length() - 1) // checking that no exception will be thrown 
     c=polinom.charAt(i+1); 
    else{ 
     if(polinom.charAt(i)=='^' && i < polinom.length() - 1){ // same 
      v=Integer.parseInt(Character.toString(polinom.charAt(i+1))); 
      coef1[v]=-Integer.parseInt(Character.toString(c)); 
      System.out.print(coef1[v]); 
     } 
    } 
} 
0

在这里的第二行,你正在使用

for(i=0;i<polinom.length()+1;i++){ 

+1应该是-1

0

我想变数polinom是一个字符串。

Your're循环超出了字符串的结尾:

for(i=0;i<polinom.length()+1;i++) 

应该

for(i=0;i<polinom.length()-1;i++) 
+0

您的答案与XLAnt相同,如果您没有新的东西,那么不需要复制粘贴,我认为它是更好地拥有新的东西。 –

+0

@BahramdunAdil:你是对的,但是我只有在发布我的回复后才看到这个答案。 –

+0

好的,这只是一个建议,有一个独特的答案。 –