How to keep switch statement continuing in Java(如何在 Java 中保持 switch 语句继续)
问题描述
我希望重复以下菜单:
选择一个选项
1 - 查找
2 - 随机播放
3 - 洗牌
这样当用户选择一个选项时(这将被执行),之后他们也可以选择其他选项.
So that when a user selects an option (and this will be executed), afterwards they can select other options as well.
问题:我的代码使菜单不断重复.
Problem: My code keeps the menu repeating without stopping.
import java.util.Scanner;
public class MainMenu {
public static void main(String[] args) {
int userChoice;
userChoice = menu();
}
private static int menu() {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose an Option");
System.out.println("1 - FIND");
System.out.println("2 - IN-SHUFFLE");
System.out.println("3 - OUT-SHUFFLE");
int choice = scanner.nextInt();
boolean quit = false;
do {
System.out.println("Choose an Option");
switch (choice) {
case 1:
System.out.println("
1 - FIND
");
//Deck.findTop();
break;
case 2:
System.out.println("
2 - IN-SHUFFLE
");
// call method
break;
case 3:
System.out.println("
3 - OUT-SHUFFLE
");
// call method
break;
default:
System.out.println("
Invalid Option");
break;
}
}
while (!quit);
return choice;
}
}
我不知道如何才能阻止它不断重复.
I'm not sure how I can stop it from constantly repeating.
推荐答案
试试这个.您只需要将退出移出循环并将选项和用户选择带入循环.
try this. You just have to move quit out of loop and bring in opions and userchoice into loop.
import java.util.Scanner;
public class Switchh {
static boolean quit = false;
public static void main(String[] args) {
int userChoice;
userChoice = menu();
}
private static int menu() {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("Choose an Option");
System.out.println("1 - FIND");
System.out.println("2 - IN-SHUFFLE");
System.out.println("3 - OUT-SHUFFLE");
choice = scanner.nextInt();
System.out.println("Choose an Option");
switch (choice) {
case 1:
System.out.println("
1 - FIND
");
//Deck.findTop();
break;
case 2:
System.out.println("
2 - IN-SHUFFLE
");
// call method
break;
case 3:
System.out.println("
3 - OUT-SHUFFLE
");
// call method
break;
default:
System.out.println("
Invalid Option");
quit = true;
break;
}
}
while (!quit);
return choice;
}
}
这篇关于如何在 Java 中保持 switch 语句继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中保持 switch 语句继续


- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01