本文介绍了字符串索引超出异常java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的类中调用函数时,我收到以下错误:
java.lang.StringIndexOutOfBoundsException:String索引超出范围:-1
虽然我使用系统打印来查看输入我正在传递substring()函数,一切似乎都是对的。函数isContained()返回一个布尔值,用于定义作为参数传递的子串是否在单词列表中。我的代码是:(int i = 0; i< = size; i ++)
$($)

 = i + 1; j< = size; j ++)
if(isContained(str.substring(i,ji)))
System.out.println(str.substring(i,ji));

其中size是字符串(str)的大小我正在传递函数

解决方案

您正在调用 str.substring(i,ji)这意味着 substring(beginIndex,endIndex),而不是 substring(beginIndex,lengthOfNewString)



这种方法的假设之一是 endIndex 大于或等于 beginIndex ,如果不是新索引的长度将为负数,并且其值将在 StringIndexOutOfBoundsException 中抛出。



也许您应该更改方法,如 str.substring(i,j)






另外,如果 size 是<$ c $ (int i = 0; i< = size; i ++)$ c $ str $ / code code $

应该是

 (int i = 0; i< size; i ++)


I am getting the following error when calling a function from within my class:java.lang.StringIndexOutOfBoundsException: String index out of range: -1Although I used a system prints to see the inputs I am passing in the substring() function and everything seems to be right. The function isContained() returns a boolean value defining whether the substring passed as a parameter is in a list of words. My code is:

for(int i=0; i<=size; i++)
    for(int j=i+1; j<=size; j++)
        if(isContained(str.substring(i,j-i)))
            System.out.println(str.substring(i,j-i));

where size is the size of the string (str) I am passing in the function

解决方案

You are calling str.substring(i, j-i) which means substring(beginIndex, endIndex), not substring(beginIndex, lengthOfNewString).

One of assumption of this method is that endIndex is greater or equal beginIndex, if not length of new index will be negative and its value will be thrown in StringIndexOutOfBoundsException.

Maybe you should change your method do something like str.substring(i, j)?


Also if size is length of your str then

for (int i = 0; i <= size; i++)

should probably be

for (int i = 0; i < size; i++)

这篇关于字符串索引超出异常java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 21:21