gpt4 book ai didi

java - "...cannot be resolved to a variable."为什么不呢?

转载 作者:行者123 更新时间:2023-12-01 10:20:56 26 4
gpt4 key购买 nike

public int getEntityIndex(String name){ 
for(int i = 0; i < entities.length; i++){
if(entities[i].getName().toUpperCase().equals(name.toUpperCase())){
break;
}
}

return i;
}

此代码产生错误:i 无法解析为变量。我猜测 for 循环声明内声明的变量超出了该方法其余部分的范围,但我无法找到有关此问题的任何信息。

分析代码一段时间后,我开始发现使用它是一个坏主意(如果entities[i]永远不等于name怎么办?该方法即使未找到匹配项,也会返回 entities.length - 1。我想我会使用 while(!found) 方法。

澄清一下,我不是在问如何解决这个问题。我想问一下为什么会出现这个错误。

谢谢!

最佳答案

您无法在 for 循环之外看到 i

试试这个:

public int getEntityIndex(String name) { 
for(int i = 0; i < entities.length; i++){
if(entities[i].getName().toUpperCase().equals(name.toUpperCase())){
return i;
}
}

return -1;
}

PS:你也可以使用

entities[i].getName().equalsIgnoreCase(name)

而不是

entities[i].getName().toUpperCase().equals(name.toUpperCase())

关于java - "...cannot be resolved to a variable."为什么不呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35630600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com