Switch case for two INT variables
java, switch-statement
Solution
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);
Problem
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