Switch case for two INT variables

前端 未结 6 1408
生来不讨喜
生来不讨喜 2021-01-12 19:07

Consider the following code :

if (xPoint > 0 && yPoint > 0) {
    m_navigations = Directions.SouthEast;
}
else if (xPoint > 0 && yP         


        
6条回答
  •  忘掉有多难
    2021-01-12 19:32

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

    So you can just call:

    m_navigations = Direction.getDirectionByPoints(xPoint,yPoint);
    

提交回复
热议问题