スレッドの例外 "main" java.lang.StringIndexOutOfBoundSexception:文字列インデックスの範囲外:-60
-
21-12-2019 - |
質問
スレッドの例外 "main" 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));
}
}
. 解決
問題は、パラメータを使用してsubstring(beginIndex, endIndex)
を呼び出しようとしていることです。
beginIndex = x + 1 = 61
endIndex = 1
.
substring
Docsによると:
この文字列の部分文字列である新しい文字列を返します。部分文字列 指定されたBeainIndexから始まり、でキャラクタに伸びます。 Index EndIndex - 1.したがって、部分文字列の長さは EndIndex-BeginIndex。
これは1 - 61 = -60
の長さになります。それが例外の理由です:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -60 ...
.
これは、このメソッドの使用方法について、いくつかの例(DOCS)です。
"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++) {
...
}
. 他のヒント
部分記録方法。
public String substring(int beginIndex)
.
または
public String substring(int beginIndex, int endIndex)
.
パラメータ: これはパラメータの詳細です:
beginIndex -- the begin index, inclusive .
endIndex -- the end index , exclusive.`
. 所属していません StackOverflow