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
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);
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..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With