java - 在 Switch 菜单上使用 do-while 循环

标签 java switch-statement

如果在提示“请输入您的模块选择”时使用 do while 循环选择了 1 - 11 以外的任何字符,我会尝试使程序返回到菜单列表...

目前,即使用户没有选择有效选项,程序也会继续运行

我希望在“请选择一个有效的模块”之后它会返回到菜单列表。

Scanner scanner = new Scanner(System.in);
    
public void moduleSelection() {

    
    System.out.println("1\t Algorithms");
    System.out.println("2\t Advanced Programming");
    System.out.println("3\t Computer Architecture and Operating Systems");
    System.out.println("4\t Artificial intelligence and Machine Learning");
    System.out.println("5\t Computer and Mobile Networks");
    System.out.println("6\t Software Engineering");
    System.out.println("7\t Big Data Analyics");
    System.out.println("8\t Cyber Security Threats");
    System.out.println("9\t Research Methods");
    System.out.println("10\t Research Project Proposal");
    System.out.println("11\t Individual Research Project");
    

    System.out.println("Please entire your Module choice");
    
    int choice;
    
    choice = scanner.nextInt();
    
    switch (choice)
    {
    case 1: System.out.println("Algorithms");
    break;
    case 2: System.out.println("Advanced Programming");
    break;
    case 3: System.out.println("Computer Architecture and Operating Systems");
    break;
    case 4: System.out.println("Artificial intelligence and Machine Learning");
    break;
    case 5: System.out.println("Computer and Mobile Networks");
    break;
    case 6: System.out.println("Software Engineering");
    break;
    case 7: System.out.println("Big Data Analytics");
    break;
    case 8: System.out.println("Cyber Security Threats");
    break;
    case 9: System.out.println("Research Methods");
    break;
    case 10: System.out.println("Research Project Proposal");
    break;
    case 11: System.out.println("Individual Research Project");
    break;
    default: System.out.println("Please select a valid Module");
    break;
    }
    
}

最佳答案

a.定义一个变量来验证用户是否输入了有效数字。 b.在 do while 循环中,检查数字是否有效

例如:

do{
System.out.println("Please entire your Module choice");

int choice;

choice = scanner.nextInt();
boolean invalidChoice=false;
switch (choice){
case 1:
...
break;
case 2:
...
break;

default: 
invalidChoice=true;
print ("Please enter valid choice");

} while(invalidChoice);

关于java - 在 Switch 菜单上使用 do-while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122986/

相关文章:

mongodb - 具有多个条件的聚合 Switch Case 语法

c++ - switch case 语句中包含成员变量 in case

Java如何为按钮分配id并检索它们?

java - 在 Eclipse 中查找 TODO 标签

java - 在 Android 中使用 firestore 仅使用用户名和密码进行身份验证

PHP 允许在 switch 语句中使用无效代码

C++ 完全跳过一个开关

c - 当 fscanf 从文本文件读取特定值时结束循环

java - 用户池不存在

java - Android 线程上的 fragment 替换(...)