java - 在 switch 语句中循环
问题描述
我想知道在 switch 语句中循环的最有效方法是什么。下面我有一个 userInput 变量,如果在这里可以更好地实现 if/then 语句以继续我的菜单选择,直到输入 -1 以退出我的程序,或者如果 do/while 循环更合适,我想提出建议。
import java.util.Scanner;
public class VirtualZoo
{
public static void main(String[] args)
{
// Options
final int catType = 0,
dogType = 1,
duckType = 2,
exit = -1;
// create Scanner
Scanner input;
input = new Scanner(System.in);
int userInput;
System.out.println("Welcome to the Zoo");
System.out.println("Pick select an animal to visit");
System.out.println("=================================");
System.out.println("===========MAIN MENU=============");
System.out.println("=================================");
System.out.println("== " + catType + ") Cat ===================");
System.out.println("== " + dogType + ") Dog ===================");
System.out.println("== " + duckType + ") Duck ===================");
System.out.println("== " + exit + ") EXIT ===================");
System.out.println("=================================");
System.out.println();
System.out.println();
System.out.println( "Input : ");
Scanner sc = new Scanner(System.in);
userInput = sc.nextInt();
Animal animalSelected = null;
switch (userInput)
{
case 0:
animalSelected = new Cat();
break;
case 1:
animalSelected = new Dog();
break;
case 2:
animalSelected = new Duck();
break;
case -1:
System.out.println("\n" + "Thank you for visiting the Virtual Zoo" + "\n" + "Goodbye!");
break;
default:
break;
}
if (animalSelected != null)
{
System.out.println(animalSelected);
}
}
}
解决方案
do while 循环将是合适的,因为您总是希望至少运行一次 switch case。
推荐阅读
- elasticsearch - 按多个嵌套属性过滤
- google-sheets - 逐行预测函数(google-sheets)
- kotlin - 使用 MockK 和 Kotlin 在 @SpringBootTest 中出现 UninitializedPropertyAccessException 的原因是什么?
- vue.js - 在 vuetify v-select 中隐藏所选项目
- inno-setup - Inno Setup 中消息框被抑制是什么意思?
- python - Python 中 igraph 的 Graph.Read_Ncol (csv)
- c - 放入变体时,Sublime Text 构建系统无法正常工作
- arrays - 在数组中添加元素时出现零错误 - Ruby
- node.js - Heroku 部署 Typescript
- c++ - 在新目录中使用相同的库编译时,Opencv 程序变得慢得多