英文:
Java: String index out of range: -4
问题
我得到了一个错误:“String index out of range: -4”
以下是我的代码
if (WHEREClause.substring((WHEREClause.length() - 4)) == "AND ") {
WHEREClause = WHEREClause.substring(0, (WHEREClause.length() - 4)); }
WHERECLAUSE 的值为 => "arSLC_CODE=13 AND "
如果我从代码中显示 "WHEREClause.substring((WHEREClause.length() - 4))",
我得到的是 => "AND "
所以看起来好像
if ("AND " == "AND ")
{
...我会进入这里
}
但是我却得到了一个错误:“String index out of range: -4”,并且无法进入 if 语句。请帮助,我还是新手对此不太了解
英文:
i got an error "String index out of range: -4"
heres my code below
if (WHEREClause.substring((WHEREClause.length() - 4)) == "AND ") {
WHEREClause = WHEREClause.substring(0, (WHEREClause.length() - 4)); }
the value of WHERECLAUSE IS => "arSLC_CODE=13 AND "
and if i display "WHEREClause.substring((WHEREClause.length() - 4))" from the code
i get this => "AND "
so it looks like
if("AND " == "AND ")
{
...i go inside here
}
but instead i got an error "String index out of range: -4" and can't get inside the if statement. please help still new to this
答案1
得分: 2
当比较字符串时,请使用.equals
而不是==
。==
通常仅用于比较引用或内存,而.equals
用于检查它们是否包含相同的内容。
英文:
When comparing strings use the .equals
instead of ==
. ==
is usually used only when comparing references or memory, while .equals
is used when to see if they contain the same content
答案2
得分: 0
首先,Alex Tănăsescu 是对的,使用 .equals
来比较 string
内容。
其次,看起来 WHEREClause
属性可能包含一个空字符串。你确定异常是在 if
代码块内抛出的吗?我相信它更早地出现在这段代码中:
WHEREClause.substring((WHEREClause.length() - 4))
只需检查一下该 string
是否为空。
英文:
Firstly, Alex Tănăsescu is right, use .equals
to compare string
content.
Secondly, it looks like WHEREClause
attribute may contain an empty string. Are you sure that the exception is throwing inside if
block? I'm convinced that it appears earlier in this peace of code:
WHEREClause.substring((WHEREClause.length() - 4))
Just check if the string
is empty.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论