gpt4 book ai didi

java - 从 for 循环返回 int

转载 作者:行者123 更新时间:2023-12-01 22:39:35 25 4
gpt4 key购买 nike

我正在尝试获取特定患者前面的患者数量。如何从 for 循环中返回 int?它始终返回 0。

public int pAhead(String name) {
Patient p;
int patientsAhead = 0;
for(int i= 0; i < list.size(); i++)
{
p = list.get(i); //get each object from array
String n = p.getName();
if(name.equalsIgnoreCase(n))
{
//if name passed is equal to object getName, than get the index of that object
patientsAhead = list.indexOf(p);
}
}
return patientsAhead;
}

最佳答案

首先,您不需要 list.indexOf(p); 因为您已经有了循环变量 i

返回它就可以了

if(name.equalsIgnoreCase(n)) {
return i;
}

请注意indexOf可能会导致其他结果,具体取决于您如何实现 equals 以及您正在与 Person 的姓名进行比较。

综上所述,请确保您的列表实际上包含一些元素。

关于java - 从 for 循环返回 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403067/

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