gpt4 book ai didi

java - 使用for循环和if的数组问题(JAVA)

转载 作者:行者123 更新时间:2023-12-02 10:31:20 25 4
gpt4 key购买 nike

我试图弄清楚如何让 for 循环在所有数组中进行搜索(我猜问题出在名为“z”的 for 循环或 if 语句中),但它一直在第一个数组中搜索,然后当第一个城市不等于 cityName 时转到 if 的 else 语句

提前致谢。

public String citiesNorthOf(String cityName)
{
String northOfCities = null;
for(int z = 0 ; z < _noOfCities-1 ; z++)
{
if(_cities[z].getCityName().equals(cityName))
{
for(int a = 0 ; a < _noOfCities-1 ; a++)
{

Point city1 = _cities[z].getCityCenter();
Point otherCity = _cities[a].getCityCenter();
if(city1.isUnder(otherCity))
{
northOfCities = _cities[a].getCityName();
System.out.println(northOfCities);
}
if(northOfCities.equals(null))
{
String noCitiesNorth = "There is no cities north of "+cityName;
return noCitiesNorth;
}
}
}

else
{
String noCity = "There is no city with the name: " +cityName;
return noCity;
}
}

return northOfCities;
}

最佳答案

问题是这段代码会检查第一个城市,如果不是你要找的城市,代码就会进入else block ,然后return 部分打破了循环。

可能之后需要在 else block 中将标志设置为 false。一旦循环执行,您就可以检查该标志的状态。如果为 false,则执行 else 部分中当前的代码。

以下部分中也会出现类似的问题:if(northOfCities.equals(null))。但是,我不确定这是否是您想要的行为。

编辑:这或多或少就是我的意思:

public String citiesNorthOf(String cityName)
{
String northOfCities = null;
for(int z = 0 ; z < _noOfCities-1 ; z++)
{
if(_cities[z].getCityName().equals(cityName))
{
for(int a = 0 ; a < _noOfCities-1 ; a++)
{

Point city1 = _cities[z].getCityCenter();
Point otherCity = _cities[a].getCityCenter();
if(city1.isUnder(otherCity))
{
return _cities[a].getCityName(); //If we find what we are looking for, we return the name of the city.
}
if(northOfCities.equals(null))
{
return "There is no cities north of "+cityName; //If we find our city, but we also find that there is nothing North of it, we return this error message.
}
}
}
}
return "There is no city with the name: " +cityName; //If the for loop has executed and none of the previous return statements have been executed, then, it follows that there is no city with the given name, so we return this error.
}

关于java - 使用for循环和if的数组问题(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53594228/

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