Reputation: 20565
I'm creating a chess game with java.
As you know when you start out the chess game you have two of each "Captains" (sorry I'm not sure what the term is) I have created the following switch case to create the graphical layout of the figures:
switch (j) {
case 1 || 8 : Rook tower = new Rook(""); return tower.getBrik();
case 2 || 7 :
case 3 || 6 : Bishop bishop = new Bishop(""); return bishop.getBrik();
case 4 : King king = new King(""); return king.getBrik();
case 5 : Queen queen = new Queen(""); return queen.getBrik();
}
Where the getBrik() method is a Node that returns an imageview.
Now as you can see my case 2 and 3 are my failed attempt to do two cases in one.
Is this even possible and if so how?
Upvotes: 6
Views: 11726
Reputation: 1129
I assume you tried OR by putting ||, but in switch case statements you cant use this operator. Therefore you just use if
if(j==1 || j==8){
Rook tower = new Rook("");
return tower.getBrik();
}else if(j==2 ||j==7 || j==6 || j==7){
Bishop bishop = new Bishop("");
return bishop.getBrik();
}
.
.
.
Upvotes: 0
Reputation: 46239
Because of fall through (execution continues to the next case
statement unless you put a break;
at the end, or of course, as in your case, a return
), you can just put the cases under each other:
...
case 1:
case 8:
Rook tower = new Rook("");
return tower.getBrik();
case 3:
case 6:
Bishop bishop = new Bishop("");
return bishop.getBrik();
...
Upvotes: 18