字符串索引越界异常java [英] String index out of bounds exception java

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

问题描述

从我的类中调用函数时出现以下错误:java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1虽然我使用系统打印来查看我在 substring() 函数中传递的输入,但一切似乎都是正确的.函数 isContained() 返回一个布尔值,定义作为参数传递的子字符串是否在单词列表中.我的代码是:

I am getting the following error when calling a function from within my class: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 Although 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));

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

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

推荐答案

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

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

此方法的一个假设是endIndex大于或等于beginIndex,否则新索引的长度将为负数,其值将被抛入StringIndexOutOfBoundsException.

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.

也许你应该改变你的方法做一些像 str.substring(i, j) 的事情?

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

此外,如果 size 是您的 str 的长度,则

Also if size is length of your str then

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

应该是

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆