【问题标题】:How to write the code if the direction is opposite of the other?如果方向相反,如何编写代码?
【发布时间】:2015-03-22 03:24:51
【问题描述】:

我有一个名为 Direction 的枚举类,它有对象 S, N, W, E, and none(南、北、东、西和无)。我有一个方法public boolean isOpposite(Direction other) 应该报告给定方向是否与另一个相反。 none 永远不会与其他任何事物相反,但 N / S 是相反的,E / W 是相反的。那么,如果方向与传递的对象相反,我如何检查布尔值?

public enum Direction {

    N, E, S, W, none;

    public Direction cycle()
    {
        if (this.equals(Direction.N))
            return Direction.E;
        else if(this.equals(Direction.E))
            return Direction.S;
        else if(this.equals(Direction.S))
            return Direction.W;
        else if(this.equals(Direction.W))
            return Direction.N;
        else if(this.equals(Direction.none))
            return none;

        return null;
    }

    public Direction getOpposite()
    {
        if(this.equals(Direction.N))
            return Direction.S;
        else if(this.equals(Direction.S))
            return Direction.N;
        else if(this.equals(Direction.E))
            return Direction.W;
        else if(this.equals(Direction.W))
            return Direction.E;
        else if(this.equals(Direction.none))
            return Direction.none;

        return null;
    }

    public boolean isOpposite(Direction other)
    {
        //???
    }

}

【问题讨论】:

  • 你有没有尝试过?
  • 哇,已经投了反对票.. 是的,我已经编辑了代码,但在想出正确的方法来处理 isOpposite() 方法时遇到了困难..@IsmailBadawi

标签: java enums


【解决方案1】:
return getOpposite() == other;

【讨论】:

  • 你能澄清你的答案吗?
  • @joshua 您已经在getOpposite 方法中自己完成了艰苦的工作。要检查this 是否与other 相对,您只需检查this.getOpposite() 是否与other 相同。
  • 感谢您的快速回复,例如,getOpposite() == other 类似于 N == N 或 S ==S ??
  • 是的。顺便说一句,您不需要将.equals() 用于枚举,因此您可以使用== 来简化自己的代码。
猜你喜欢
  • 1970-01-01
  • 2018-05-21
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多