java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java.lang.StringIndexOutOfBoundsException: String index out of range: -1

解决java.lang.StringIndexOutOfBoundsException: String index out of range: -1错误问题

作者:Archie_java

这篇文章主要介绍了解决java.lang.StringIndexOutOfBoundsException: String index out of range: -1错误问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

字符串截取下标越界

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)

出错代码

result.put("value", valueBuilder.toString().substring(0,valueBuilder.toString().length()-1));

修改后代码

if (StringUtils.isNotBlank(valueBuilder.toString()) && valueBuilder.toString().length() >0){
                            result.put("value", valueBuilder.toString().substring(0,valueBuilder.toString().length()-1));
                        }

心得:

/**
 * Thrown by {@code String} methods to indicate that an index
 * is either negative or greater than the size of the string.  For
 * some methods such as the charAt method, this exception also is
 * thrown when the index is equal to the size of the string.
 */
public
class StringIndexOutOfBoundsException extends IndexOutOfBoundsException {
    private static final long serialVersionUID = -6762910422159637258L;
 
    /**
     * Constructs a {@code StringIndexOutOfBoundsException} with no
     * detail message.
     *
     * @since   JDK1.0.
     */
    public StringIndexOutOfBoundsException() {
        super();
    }
 
    /**
     * Constructs a {@code StringIndexOutOfBoundsException} with
     * the specified detail message.
     *
     * @param   s   the detail message.
     */
    public StringIndexOutOfBoundsException(String s) {
        super(s);
    }
 
    /**
     * Constructs a new {@code StringIndexOutOfBoundsException}
     * class with an argument indicating the illegal index.
     *
     * @param   index   the illegal index.
     */
    public StringIndexOutOfBoundsException(int index) {
        super("String index out of range: " + index);
    }
}

总共有以下几个方法会抛出该异常:

String.substring()

String.charAt()

String.codePointAt()

String.codePointBefore()

String.subSequence()

String.getChars()

String.getBytes()

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文