Wires77
Wires77

Reputation: 351

Set a variable and check equality in one line

I'm creating a maze program to get some more practice in Java. I have a method that moves the player, and it returns a boolean value if the move was successful (i.e. it didn't run into a wall).

Here is the method in question:

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

Obviously, this will always return false. I was wondering if there is a way to check if currentLocation didn't change (or is equal to the returned value of maze.movePlayer(...) and set them equal if they aren't). I don't know if it is possible to do this without calling the method twice or using a local variable.

I hope this makes sense!

Upvotes: 2

Views: 3094

Answers (3)

Dave Newton
Dave Newton

Reputation: 160191

This works as you expect, using a single line, assuming a reasonable equals method.

(I pass a Location instead of transforming a Direction, but the mechanics are identical.)

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

This uses a simple Location implementation; note the equals, auto-generated by IntelliJ:

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

}

Upvotes: 2

rgerganov
rgerganov

Reputation: 2232

Another way to do this using temp variable:

public boolean move(Direction direction) {
    Location oldLocation = currentLocation;
    currentLocation = maze.movePlayer(this, direction));
    return !oldLocation.equals(currentLocation);
}

Upvotes: 0

Kevin Mangold
Kevin Mangold

Reputation: 1155

You can use the conditional operator:

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

Upvotes: 4

Related Questions