【问题标题】:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -60线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:-60
【发布时间】:2014-01-27 13:11:05
【问题描述】:

线程“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));

    }

}

【问题讨论】:

标签: java substring indexoutofboundsexception


【解决方案1】:

问题是您尝试使用参数调用substring(beginIndex, endIndex)

beginIndex = x + 1 = 61
endIndex = 1

根据substring docs:

返回一个新字符串,它是该字符串的子字符串。子串 从指定的 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 &lt; splitText.size()

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

【讨论】:

  • 顺便说一句,for (int y = 0; splitText.size() &lt; y;y++){ 应该是 for (int y = 0; y &lt; splitText.size();y++){
  • 哇,非常感谢!不敢相信我错过了这么简单的东西。非常感谢您的帮助。 (感谢 ichramm 的最后提示)
【解决方案2】:

由于子串方法。

public String substring(int beginIndex)

public String substring(int beginIndex, int endIndex)

参数: 这是参数的详细信息:

beginIndex -- the begin index, inclusive .

endIndex -- the end index , exclusive.`

【讨论】:

    猜你喜欢
    • 2013-01-20
    • 1970-01-01
    • 2019-03-11
    • 2015-06-30
    • 2012-07-27
    • 2012-11-27
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多