Java switch double duplicate case

爱⌒轻易说出口 提交于 2020-01-21 11:46:10

问题


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?


回答1:


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();
...



回答2:


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();
}
.
.
.


来源:https://stackoverflow.com/questions/16103236/java-switch-double-duplicate-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!