两个 INT 变量的切换案例 [英] Switch case for two INT variables

查看:25
本文介绍了两个 INT 变量的切换案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

这篇关于两个 INT 变量的切换案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆