Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No. of variables in a switch statement - Java

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

enum Facing { North, South, East, West }

enum Forward { Right, Left }

Forward forward;

Facing facing;

Integer myNumber;

So it looks like this? And if so how would I go about implementing

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

I know this is wrong but wondered whether such a technique might work and how would I implement it?

like image 553
maclunian Avatar asked Dec 04 '22 08:12

maclunian


1 Answers

Eng.Fouad gives one way around that.

Another altenative might be to create a more complex Facing enum like 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();
}

Such a construct also allows for easy chaining so that you could write a generic reverse routine like this:

Facing reverse(Facing facing) { return facing.right().right(); }
like image 67
Ben Hocking Avatar answered Dec 06 '22 09:12

Ben Hocking