我正在尝试使用Field类中的getFreeAdjacentLocation方法,但是我从CleverSheep类中收到一条错误,指出它找不到符号 - 方法getFreeAdjacentLocation(Location)'
我有一个类Field
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);
}
}
}
}
答案 0 :(得分:1)
您的方法称为getFreeAdjacentLocations()
,但在第二个区块中,您调用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
。