1

私はJavaでもう少し練習するために迷路プログラムを作成しています。プレーヤーを移動するメソッドがありboolean、移動が成功した場合(つまり、壁にぶつからなかった場合)に値を返します。

問題の方法は次のとおりです。

public boolean move(Direction direction) {
    if(currentLocation == (currentLocation = maze.movePlayer(this, direction))) {
        return false;
    } else {
        return true;
    }
}

明らかに、これは常にfalseを返します。変更されていないかどうかを確認する方法があるかどうか疑問に思いましたcurrentLocation(または、の戻り値と等しく、変更されていない場合は等しくmaze.movePlayer(...)設定します)。メソッドを2回呼び出すか、ローカル変数を使用せずにこれを実行できるかどうかはわかりません。

これが理にかなっていることを願っています!

4

3 に答える 3

3

条件演算子を使用できます。

public boolean move(Direction direction) {
     return (currentLocation == (currentLocation = maze.movePlayer(this, direction))) ? false : true;
}
于 2012-07-05T16:26:54.537 に答える
2

equalsこれは、妥当な方法を想定して、1行を使用して期待どおりに機能します。

(私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実装を使用します。equalsIntelliJによって自動生成されたに注意してください。

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;
    }

}
于 2012-07-05T16:49:41.067 に答える
0

一時変数を使用してこれを行う別の方法:

public boolean move(Direction direction) {
    Location oldLocation = currentLocation;
    currentLocation = maze.movePlayer(this, direction));
    return !oldLocation.equals(currentLocation);
}
于 2012-07-05T16:33:53.270 に答える