Switch case for two INT variables

前端 未结 6 1348
生来不讨喜
生来不讨喜 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:24

    The simplest and easiest solution is to use multidimensional arrays.

    public class CalculateDirections {
        private final static Directions DIRECTION_MAP[][] = {
            {Directions.NorthWest, Directions.North, Directions.NorthEast},
            {Directions.West, null, Directions.East},
            {Directions.SouthWest, Directions.South, Directions.SouthEast},
        };
    
        public static void main(String[] args) {
            int x = Integer.valueOf(args[0]);
            int y = Integer.valueOf(args[1]);
    
            int signumX = Integer.signum(x);
            int signumY = Integer.signum(y);
            Directions direction = DIRECTION_MAP[signumY + 1][signumX + 1];
    
            System.out.println(direction);
        }
    }
    
    enum Directions {
        SouthEast, NorthEast, SouthWest, NorthWest, North, South, East, West
    }
    

    There are several advantages:

    • No if/else cascades which take some runtime and are hard to manage.
    • No creation of temporary Strings. In a tight game loop this may be important.
    • No linear search through lists or arrays.

提交回复
热议问题