使用switch和scanner类java使用用户选择
我在使用scanner类从键盘选择一些菜单时遇到一些问题 我试图从main方法执行下面的逻辑使用switch和scanner类java使用用户选择,java,Java,我在使用scanner类从键盘选择一些菜单时遇到一些问题 我试图从main方法执行下面的逻辑 StudentBO country = new StudentBO(); Scanner sc = new Scanner(System.in); int selection; System.out.println("Menu : "); System.out.println("Type any number between 1 and 6"); System.out.println("1)Create
StudentBO country = new StudentBO();
Scanner sc = new Scanner(System.in);
int selection;
System.out.println("Menu : ");
System.out.println("Type any number between 1 and 6");
System.out.println("1)Create a new student");
System.out.println("2)details specific student");
System.out.println("3)details of all students");
System.out.println("4)details of the student age details");
System.out.println("5)details of the student personal info");
System.out.println("6)Exit");
selection = sc.nextInt();
switch (selection)
{
case 1 :
System.out.println("Enter studentName ");
sc = new Scanner(System.in);
String studentName= sc.nextLine();
Student studentInfo = student.createStudent(studentName);
System.out.println("Do you want to continue? Type Yes / No");
Scanner sc1 = new Scanner(System.in);
case 2 :
break;
case 3 :
break;
case 4 :
break;
case 5 :
break;
case 6 :
break;
}
当我选择选项1时,将创建学生,然后我必须输入是或否,如果用户选择是,则再次从选项菜单(1、2、3、4、5或6)提示用户,如果用户选择否,则中断
我面临的问题
在读取第二个输入时,可以使用带布尔值的while循环作为退出
StudentBO country = new StudentBO();
Scanner sc = new Scanner(System.in);
int selection;
boolean exit = false;
while (!exit)
{
System.out.println("Menu : ");
System.out.println("Type any number between 1 and 6");
System.out.println("1)Create a new student");
System.out.println("2)details specific student");
System.out.println("3)details of all students");
System.out.println("4)details of the student age details");
System.out.println("5)details of the student personal info");
System.out.println("6)Exit");
selection = sc.nextInt();
switch (selection)
{
case 1 :
System.out.println("Enter studentName ");
sc = new Scanner(System.in);
String studentName= sc.nextLine();
Student studentInfo = student.createStudent(studentName);
System.out.println("Do you want to continue? Type Yes / No");
Scanner sc1 = new Scanner(System.in);
if (sc1.next().equalsIgnoreCase("no"))
exit = true;
break;
case 2 :
break;
case 3 :
break;
case 4 :
break;
case 5 :
break;
case 6 :
break;
}
}
似乎您正在寻找某种类型的循环。系统会提示用户输入是或否,如果输入是,则会再次提示用户输入一些选项1、2、3、4、5或6,但输入是后,控件将转到案例2,而不会提示用户输入1、2、3、4、5或6。此操作有效,但所有菜单选项仅在java程序运行时第一次显示,在下一次提示中,用户只需输入选项,如1、2、3、4、5或6,而不会在上次打印后移动while循环时再次显示所有菜单选项(退出消息)