有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何创建菜单控制台循环?

我必须创建一个菜单供用户选择,当用户输入不正确的选项时,我需要它循环。到目前为止我掌握的代码;它会持续循环,或者当我运行程序时,它会给我所有选择的输出,而不是我专门输入的输出。我的循环是一个带有switch语句的do/while循环。我会把我试过的贴在下面。我只需要知道我的循环代码是否正确,如果不正确,如何修复它?如果需要任何澄清,请询问。我很抱歉,如果我听起来真的很懒或愚蠢,我只是想能够理解这一点,有时,我就是不理解,所以请寻求一些额外的帮助

 do
{

int selection = 0;


System.out.println("Please choose one of the following to determine whether you are a new or existing cutomer:");
System.out.println("[1]- Existing Customer");
System.out.println("[2] - New Customer");

System.out.println("Insert selection:");


switch (selection)
{
case 1:
System.out.println("Welcome Back" + userName);
break;

case 2:
System.out.println("Hello, I see you are a new customer,");
System.out.println("let's get your account setup!");
break;

case 3:
default: System.out.println("That is not a vaild. Please select from one of the following options.");
break;
}
while (selection !=3);

共 (1) 个答案

  1. # 1 楼答案

             String[] options = new String[]{
               "Existing Customer",
               "New Customer"
             };   
    
            int selection = 0;
    
            do{
                System.out.println("Please choose one of the following to determine whether you are a new or existing customer");
                for (int i = 0; i < options.length; i++) {
                    System.out.printf("[%s] - %s%n",i+1, options[i]);
                }
                String input = new Scanner(System.in).nextLine();
                try{
                    selection = Integer.parseInt(input);
                }catch(NumberFormatException e){
                    System.out.println("That is not a vaild. Please select from one of the following options.");
                    selection = 0;
                }
            }while(selection <= 0 || selection > options.length);
    
            switch(selection){
                case 1:
                    System.out.println("Welcome Back");
                    break;
                case 2:
                    System.out.println("Hello, I see you are a new customer,");
                    System.out.println("let's get your account setup!");
                    break;
            }