跳出 switch 语句执行一个 case
Break out of switch statement execute one case
基本上,我试图让 switch 语句只执行一次。并且不执行所有这些。
假设玩家的物品栏中有所有钥匙。
我只想执行一个案例,而不是遍历所有案例。
(我只想看到一个执行)
public int[] allKeys = {1543, 1544, 1545, 1546, 1547, 1548};
if (player.getInventory().containsAny(allKeys)) {
for (int id : allKeys) {
switch(id) {
case 1543:
System.out.println("executed");
break;
case 1544:
System.out.println("executed");
break;
case 1545:
System.out.println("executed");
break;
case 1546:
System.out.println("executed");
break;
case 1547:
System.out.println("executed");
break;
case 1548:
System.out.println("executed");
break;
default:
System.out.println("error!");
}
}
}
你的 switch
只做 "one at a time" - 事实上你的开关处于 for 循环中导致你出现问题...
您可以在开关 switch(x) { ... } break;
之后放置一个 "break",但实际上为什么在您不想循环时循环 - 只需打开第一个键即可。
您目前是 运行 for 循环中的 switch case,它遍历数组 allKeys 中的每个 id。因为您假定用户拥有 allKeys,所以我将删除 for 循环,并选择您希望用户执行的任何键,然后让该键通过 switch 语句。
基本上,我试图让 switch 语句只执行一次。并且不执行所有这些。 假设玩家的物品栏中有所有钥匙。 我只想执行一个案例,而不是遍历所有案例。 (我只想看到一个执行)
public int[] allKeys = {1543, 1544, 1545, 1546, 1547, 1548};
if (player.getInventory().containsAny(allKeys)) {
for (int id : allKeys) {
switch(id) {
case 1543:
System.out.println("executed");
break;
case 1544:
System.out.println("executed");
break;
case 1545:
System.out.println("executed");
break;
case 1546:
System.out.println("executed");
break;
case 1547:
System.out.println("executed");
break;
case 1548:
System.out.println("executed");
break;
default:
System.out.println("error!");
}
}
}
你的 switch
只做 "one at a time" - 事实上你的开关处于 for 循环中导致你出现问题...
您可以在开关 switch(x) { ... } break;
之后放置一个 "break",但实际上为什么在您不想循环时循环 - 只需打开第一个键即可。
您目前是 运行 for 循环中的 switch case,它遍历数组 allKeys 中的每个 id。因为您假定用户拥有 allKeys,所以我将删除 for 循环,并选择您希望用户执行的任何键,然后让该键通过 switch 语句。