首页 > 解决方案 > 在 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);
 }
}
}

标签: javaloopsif-statementdo-while

解决方案


do while 循环将是合适的,因为您总是希望至少运行一次 switch case。


推荐阅读