Java:字符串索引超出范围:-4

huangapple go评论66阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年4月7日 15:26:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/61074800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定