2017-11-11 52 views
-2
我在使用扫描仪类的从键盘 我试图从主方法

使用开关和扫描仪级Java

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)中提示用户,如果用户选择否,然后休息。

问题我面临的

  1. 如何退一万例的执行之后要选择的选项菜单。我想回到提示用户选择菜单后的情况1

  2. 如何从一种情​​况切换到另一种情况。在情况1中,基于某些条件,我想直接调用情况2。那可能吗?

+0

好像你正在寻找某种类型的循环。 –

+0

[使用next(),nextInt()或其他nextFoo()?](https://stackoverflow.com/q/13102045)后扫描程序跳过nextLine() – Pshemo

+0

提示用户输入是或否,如果输入是的,那么用户必须提示输入一些选择1,2,3,4,5或6,但是在输入是后,控制转到case2,而不是提示输入1,2,3,4,5或6 – user2883028

回答

0

您可以在读取第二个输入时使用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; 
      } 
} 
+0

这有效,但所有菜单选项仅在java程序运行时第一次显示,从下次提示开始,用户只需输入1,2,3,4,5或6等选项,而不显示所有菜单选项 – user2883028

+0

然后在最后一次打印后退出while循环(退出消息) – Melron