2014-01-09 85 views
-2

在線程異常「主」 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-60異常在線程「主」 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-60

我不斷得到這個錯誤,我一直試圖弄清楚,但我不能!我剛剛開始使用Java,因此非常感謝所有幫助!這裏是我的代碼:

//This method takes large amounts of text and formats 
//them nicely in equal lenth lines for the console. 

public void print(String a){ 

    String textLine = a; 
    int x = 60; 
    List<String> splitText = new ArrayList<String>(); 

    //limits the amount of characters in a printed line to 60 + the next word. 
    while (textLine.length() > 60) { 

     if (textLine.substring(x+1,1) == " "){   
      splitText.add(textLine.substring(0,x+1)); 
      textLine = textLine.substring(x+2); 
      x = 0; 
     }   
     else {   
      x++; 
     } 
    } 

    splitText.add(textLine); 

    for (int y = 0; splitText.size() < y;y++){ 

     System.out.println(splitText.get(y)); 

    } 

} 
+0

你也可能需要閱讀http://stackoverflow.com/questions/513832/how -do-i-compare-strings-in-java –

回答

0

的問題是,你正在試圖調用substring(beginIndex, endIndex)與參數:

beginIndex = x + 1 = 61 
endIndex = 1 

根據substring文檔:

返回一個新字符串,它是一個此字符串的子字符串。子字符串 從指定的beginIndex開始,並擴展到 index endIndex - 1的字符。因此子字符串的長度爲 endIndex-beginIndex。

這將落在1 - 61 = -60的長度。這是異常的原因:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -60 ... 

以下是一些例子(從文檔),如何使用這個方法:

"hamburger".substring(4, 8) returns "urge" 
"smiles".substring(1, 5) returns "mile" 

編輯:

另一個錯誤(感謝@ichramm)在您打印結果的for-loop中。所述結束條件y < splitText.size()

for (int y = 0; y < splitText.size(); y++) { 
    ... 
} 
+1

btw,'for(int y = 0; splitText.size()

+0

哇,謝謝你!不能相信我錯過了這麼簡單的事情。真的很感謝幫助。 (並感謝最後一個提示ichramm) – user3176159

0

由於子方法。

public String substring(int beginIndex) 

public String substring(int beginIndex, int endIndex) 

參數: 下面是參數的細節:

beginIndex -- the begin index, inclusive . 

endIndex -- the end index , exclusive.` 
相關問題