我正在尝试简化 Card 类,想知道是否有任何方法可以在 switch 语句中使用一系列值?
考虑:
if((card<14))
suit="Hearts";
else
if((card>14)&&(card<27))
suit="Clubs";
etc.
相反,我想使用 switch 语句,例如:
switch(card){
case1: through case13:
suit="Hearts";
break;
etc.
我无法在 Java 教程中找到任何暗示存在这种开关变体的内容。但是有吗?
最佳答案
你能做的最好的事情就是这样(见下文)。所以在某些情况下(没有双关语意:)),最好使用 if 语句。
switch(card){
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
suit="Hearts";
break;
}
但是,您可以考虑的另一种方法是使用 map 。
Map<Integer, String> map = new HashMap<Integer, String>();
for (int i = 1; i <= 14; ++i) {
map.put(i, "Hearts");
}
for (int i = 15; i <= 26; ++i) {
map.put(i, "Clubs");
}
然后您可以使用 map 查找卡片的花色。
String suit1 = map.get(12); // suit1 will be Hearts after the assignment
String suit2 = map.get(23); // suit2 will be Clubs after the assignment
关于java - 我可以在单个开关中使用一系列值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9829433/