gpt4 book ai didi

java - 如何调用另一个类中的List类型方法

转载 作者:行者123 更新时间:2023-12-01 11:47:49 25 4
gpt4 key购买 nike

我尝试使用 Field 类中的 getFreeAdjacentLocation 方法,但从 CleverSheep 类收到错误,指出“找不到符号 - 方法 getFreeAdjacentLocation(Location)”

我有一个类字段

public class Field
{
// some fields
// constructor
// other methods
public List<Location> getFreeAdjacentLocations(Location location)
{
validLocation(location);
List<Location> free = new LinkedList<Location>();
List<Location> adjacent = adjacentLocations(location);
for(Location next : adjacent) {
if(getObjectAt(next) == null) {
free.add(next);
}
}
return free;
}

我有一个聪明的羊类

public class CleverSheep
{
// constructor
public CleverSheep(Field field, Location location, int n)
{
super(field, location);
}

public void act()
{
if (isAlive()) {
Location newLocation = getField().freeAdjacentLocation(getLocation());
Location freeLocation = getField().getFreeAdjacentLocation(getLocation());
if(newLocation != null) {
moveToLocation(newLocation);
}

// If Wolf is in this location
else if (newLocation == null ) {
moveToLocation(freeLocation);
}

}
}
}

最佳答案

您的方法名为 getFreeAdjacentLocations()但在第二个 block 中,您正在调用 getFreeAdjacentLocation()没有“s”。

您可能还需要重新检查变量类型,因为返回类型为 getFreeAdjacentLocations()List<Location>freeLocation 的类型是 Location 。你需要这样的东西:

List<Location> freeLocations = getField().getFreeAdjacentLocations(getLocation());

方法moveToLocation()可能会提示,因为它可能需要一个 Location而不是一个列表。因此您需要处理 freeLocations列出并选择一个位置以传递给它。例如:

for (Location freeLocation : freeLocations) {
if (satisfiesCondition(freeLocation)) {
moveToLocation(freeLocation);
break;
}
}

哪里satisfiesCondition()是您需要实现的方法,它将返回 true如果freeLocation是您要移动到的位置。

关于java - 如何调用另一个类中的List类型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29019819/

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