Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case for two INT variables

Consider the following code :

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

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

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

Thanks

like image 507
JAN Avatar asked Apr 13 '13 18:04

JAN


2 Answers

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);
like image 132
danieln Avatar answered Sep 30 '22 23:09

danieln


Use signum to get -1, 0 or 1 on the direction like this:

String direction = Integer.signum(xPoint)+","+Integer.signum(yPoint);
switch(direction){
  case "1,1": 
    m_navigations = Directions.SouthEast;
    break;
  case "-1,0"
    m_navigations = Directions.West;
    break;

etc..
}
like image 40
bluevoid Avatar answered Sep 30 '22 22:09

bluevoid