切换两个INT变量的情况

JAN*_*JAN 6 java switch-statement

请考虑以下代码:

if (xPoint > 0 && yPoint > 0) {
    m_navigations = Directions.SouthEast;
}
else if (xPoint > 0 && yPoint < 0) {
    m_navigations = Directions.NorthEast;
}
else if (xPoint < 0 && yPoint > 0) {
    m_navigations = Directions.SouthWest;
}
else if (xPoint < 0 && yPoint < 0) {
    m_navigations = Directions.NorthWest;
}
else if (xPoint == 0 && yPoint < 0) {
    m_navigations = Directions.North;
}
else if (xPoint == 0 && yPoint > 0) {
    m_navigations = Directions.South;
}
else if (xPoint > 0 && yPoint == 0) {
    m_navigations = Directions.East;
}
else if (xPoint < 0 && yPoint == 0) {
    m_navigations = Directions.West;
}
Run Code Online (Sandbox Code Playgroud)

这是相当难看,我想用开关的情况下,但我该如何使用switch2变量?

我想过像这样 - @Frits面包车坎彭的答案,但我需要使用><运营商...

谢谢

dan*_*eln 6

你可以用枚举做任何事情.我为前两个值创建了示例,您可以继续使用其余值.

public enum Direction
{
    SouthEast(1,1),
    NorthEast(1,-1);

    int _xPoint, _yPoint;

    Direction(int xPoint, int yPoint)
    {
        _xPoint = xPoint;
        _yPoint = yPoint;
    }

    public static Direction getDirectionByPoints(int xPoint, int yPoint)
    {
        for (Direction direction : Direction.values())
        {
            if(   Integer.signum(xPoint) == direction._xPoint 
               && Integer.signum(yPoint) == direction._yPoint )
            {
                return direction;
            }
        }
        throw new IllegalStateException("No suitable Direction found");
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以打电话:

m_navigations = Direction.getDirectionByPoints(xPoint,yPoint);
Run Code Online (Sandbox Code Playgroud)