Java switch 双重重复的情况 [英] Java switch double duplicate case

查看:16
本文介绍了Java switch 双重重复的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 java 创建一个国际象棋游戏.

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

getBrik() 方法是一个返回图像视图的节点.

Where the getBrik() method is a Node that returns an imageview.

现在您可以看到我的案例 2 和 3 是我尝试将两个案例合二为一的失败尝试.

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?

推荐答案

因为 fall through (执行继续到下一个 case 语句,除非你放一个 break; 在最后,或者当然,就像你的情况一样,一个 return),你可以把这些情况放在一起:

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

这篇关于Java switch 双重重复的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆