Pergunta

How would you take a point object and flip the coordinates and switch their signs? If you wanted to add a method called flip to the code below:

    public class Point {
    private int x;
    private int y;

    // flip method goes here

}

I've tried things like:

    public class flip(){
    x = 0-x;
    y = 0-y;
    Point p = new Point(y,x);
}

But it's not working. (81,21) and I only get (-81,-21). It doesn't flip it. But method can't take any parameters, if that's even relevant. Thanks.

Foi útil?

Solução

If you want to flip the coordinates in place (so calling p.flip() modifies Point p, then this should work:

public class Point {
    private int x;
    private int y;

    public void flip() {
        int tmp = x;
        x = -y;
        y = -tmp;
    }
}

If you want the flip() method to return a new point with the coordinates flipped, then you can do this:

public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Point flip() {
        return new Point(-y, -x);
    }
}

Outras dicas

Try this:

public Point flip(Point orig){
    return new Point(-orig.y, -orig.x);
}

If you can not pass it any parameters, make them class variables.

private Point mPoint;

public void flip(){
    mPoint.x = -mPoint.y;
    mPoint.y = -mPoint.x;
}

Something like the following code would work in your situation:

public Point flip(Point point)
{
  return new Point(-point.getY(), -point.getX());
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top