gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-13 17:18:03 27 4
gpt4 key购买 nike

[2022 中国 DevOps 现状调查全面启动!>>>

字符串截取下标越界

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));
                        }
总结

StringIndexOutOfBoundsException 异常源码如下:

/**
 * 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()

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com