Fernando Aires
Fernando Aires

Reputation: 531

Incrementing an enum var to next element in Java

I'm implementing a Tic-Tac-Toe in Java, and have an enum declared like this:

public enum Player{X,O};

When a movement is made, I need to swap to the other player, and I am doing it like:

this.nextPlayer = ((this.nextPlayer == Player.X)?Player.O:Player.X);

Is there a way of automatically "increment" through the next element of an enum structure? I was wondering about having 5 or 6 different values, and wanting to swap through them without a huge code in it (and without implementing a separated method).

Upvotes: 0

Views: 504

Answers (1)

Mike Laren
Mike Laren

Reputation: 8178

You can use the ordinal() method of enums together with the modulus operator to achieve that:

this.nextPlayer = (nextPlayer.ordinal() + 1) % Player.values().length;

Upvotes: 3

Related Questions