The number of variables in a switch statement - Java

Can you include more than one variable in a switch in Java?

 enum Facing { North, South, East, West } enum Forward { Right, Left } Forward forward; Facing facing; Integer myNumber; 

What does it look like? And if so, how do I go about implementing

 switch (facing, forward) { case North, Right : facing 1 = East } 

I know this is wrong, but I wondered if such a method can work and how I implement it.

+4
source share
5 answers

You can do the following:

 switch(facing) { case North: switch(forward) { case Right: // blah blah break; } break; } 
+4
source

Eng.Fouad provides one way.

Another way to facilitate the creation of a more complex enumeration similar to this:

 enum Facing { North { Facing right() { return East; } Facing left() { return West; } }, East { Facing right() { return South; } Facing left() { return North; } }, South { Facing right() { return West; } Facing left() { return East; } }, West { Facing right() { return North; } Facing left() { return South; } }; abstract Facing right(); abstract Facing left(); } 

This design also allows easy chaining so you can write a general inverse procedure like this:

 Facing reverse(Facing facing) { return facing.right().right(); } 
+9
source

It seems to belong to Facing:

 enum Facing { North, East, South, West; public Facing turn(Forward f) { return values()[(ordinal() + (f == Forward.Right ? 1 : 3)) % 4]; } } 
+2
source

Starting with JDK 7 , you can simulate this with a line-by-line switch:

 Facing facing = Facing.North; Forward forward = Forward.Right; String facingForward = facing + "-" + forward; switch(facingForward){ case "North-Right": return East; .. } 
+2
source

You effectively model a set of state transitions when you are in a certain state (for example, to the north), certain actions (for example, turning 90 people) lead to a new state (facing east)

You can model such things with a variety of nested switch statements or some of these. I think you can do everything you can to actually model states as explicit classes, possibly derived from an abstract base class that defines actions.

I suspect that if your states or actions become a little more complicated, you will find that you need classes.

0
source

All Articles