所以我希望我的开关是如果用户选择开关(b)不,它会回到开关(a)上一个开关。我该怎么做?我对Java很陌生。
switch(a){
case 1:
System.out.println("Here are the available rooms.");
System.out.println("[1] Room No. 1");
System.out.println("[2] Room No. 2");
System.out.println("[3] Room No. 3");
System.out.println("[4] Room No. 4");
System.out.println("[5] Room No. 5\n");
System.out.print("\nWhich room would you like? [1-5]:");
b= sc.nextInt();
switch(b){
case 1:
System.out.println("Room No. 1 costs $200 per stay.");
System.out.println("[1] Yes");
System.out.println("[2] No");
System.out.print("Do you wish to proceed? :");
c=sc.nextInt();
break;
}
break;
}
您需要使用带标签的循环:
theLabel: while (true) { // whatever condition, whatever kind of loop:
switch (a) {
case 1:
// ...
switch (b) {
case 1:
// ...
continue theLabel;
}
}
}
这将跳回到外循环的开始处,因此它将再次执行 a 上的切换。
但实际上,这不是构建它的好方法。几乎总是有比使用标记循环更好的方法,例如将一些嵌套逻辑提取到方法中。
在这种情况下,我会质疑“房间 1-房间 5”的开关的使用。除非每个房间都有特定的逻辑,否则只需使用(例如)数组或列表或地图来存储每个房间的价格。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句