线程“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
文档:
返回一个新字符串,该字符串是该字符串的子字符串。子字符串从指定的BeginIndex开始,并在索引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++) {
...
}
其他提示
由于底线方法。
public String substring(int beginIndex)
.
或
public String substring(int beginIndex, int endIndex)
.
参数: 以下是参数的细节:
beginIndex -- the begin index, inclusive .
endIndex -- the end index , exclusive.`
. 不隶属于 StackOverflow