解決java.lang.StringIndexOutOfBoundsException: String index out of range: -1錯誤問題
更新時間:2025年03月22日 11:29:49 作者:Archie_java
這篇文章主要介紹了解決java.lang.StringIndexOutOfBoundsException: String index out of range: -1錯誤問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
字符串截取下標(biāo)越界
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()
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
springboot中關(guān)于自動建表,無法更新字段的問題
這篇文章主要介紹了springboot中關(guān)于自動建表,無法更新字段的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02詳解Java8如何使用Lambda表達(dá)式進(jìn)行比較
Lambda表達(dá)式,也可稱為閉包,是java8的新特性,作用是取代大部分內(nèi)部類,優(yōu)化java代碼結(jié)構(gòu),讓代碼變得更加簡潔緊湊。本文將利用Lambda表達(dá)式進(jìn)行排序比較,需要的可以參考一下2022-01-01零基礎(chǔ)寫Java知乎爬蟲之獲取知乎編輯推薦內(nèi)容
上篇文章我們拿百度首頁做了個小測試,今天我們來個復(fù)雜的,直接抓取知乎編輯推薦的內(nèi)容,小伙伴們可算松了口氣,終于進(jìn)入正題了,哈哈。2014-11-11