我正在创建一个迷宫程序,以便在Java中获得更多练习。我有一个移动玩家的方法,如果移动成功,它会返回boolean
值(即它没有碰到墙)。
以下是有问题的方法:
public boolean move(Direction direction) {
if(currentLocation == (currentLocation = maze.movePlayer(this, direction))) {
return false;
} else {
return true;
}
}
显然,这总是会返回false。我想知道是否有办法检查currentLocation
是否没有改变(或等于maze.movePlayer(...)
的返回值,如果不是则将它们设置为相等)。我不知道是否可以在不调用方法两次或使用局部变量的情况下执行此操作。
我希望这是有道理的!
答案 0 :(得分:3)
您可以使用条件运算符:
public boolean move(Direction direction) {
return (currentLocation == (currentLocation = maze.movePlayer(this, direction))) ? false : true;
}
答案 1 :(得分:2)
这可以按照您的预期使用单行,假设采用合理的equals
方法。
(我传递Location
而不是转换Direction
,但机制相同。)
public class Main {
private Location loc = new Location(0, 0);
public boolean move(Location newLoc) {
return !loc.equals(loc = newLoc);
}
public static void main(String[] args) {
Main m = new Main();
// Not same; moved from 0, 0: true--move successful.
System.out.println(m.move(new Location(42, 69)));
// Same; moved from 42, 69: false--move failed.
System.out.println(m.move(new Location(42, 69)));
// Not same; moved from 42, 69, 0: true--move successful.
System.out.println(m.move(new Location(69, 42)));
}
}
这使用简单的Location
实现;请注意由IntelliJ自动生成的equals
:
public class Location {
private int x;
private int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Location location = (Location) o;
if (x != location.x) {
return false;
}
if (y != location.y) {
return false;
}
return true;
}
}
答案 2 :(得分:0)
使用临时变量执行此操作的另一种方法:
public boolean move(Direction direction) {
Location oldLocation = currentLocation;
currentLocation = maze.movePlayer(this, direction));
return !oldLocation.equals(currentLocation);
}