两个 INT 变量的切换案例

2022-01-19 00:00:00 switch-statement java

考虑以下代码:

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

这很丑陋,我想使用 switch case ,但是如何将 switch2 变量一起使用?

This is quite ugly , and I want to use switch case , but how can I use switch with 2 variables ?

我想过类似 this - @Frits van Campen 的答案,但我需要使用 >< 运算符...

I thought about something like this - the answer of @Frits van Campen , but I need to use > and < operators ...

谢谢

推荐答案

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

You can do everything with enums. I created examples for the first two values, you can continue with the rest.

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

所以你可以打电话:

m_navigations = Direction.getDirectionByPoints(xPoint,yPoint);

相关文章