2014-11-22 124 views
0

因此,我正在编写一个基于菜单的程序,并且我陷入了一个部分。这里是我的代码:通过switch语句循环

public static void main(String [] args) throws FileNotFoundException { 
    switch (menu()) { 
     case 1: 
      System.out.println("Stub 1"); 
      menu(); 
      break; 
     case 2: 
      System.out.println("Stub 2"); 
      menu(); 
      break; 
     case 3: 
      System.out.println("Stub 3"); 
      menu(); 
      break; 
     case 4: 
      System.out.println("Program Terminated"); 
      break; 

    } 

} 

public static int menu() { 
    System.out.println("Choose a task number from the following: "); 
    System.out.println("\t1. - See histogram of name's popularity"); 
    System.out.println("\t2. - Compare two names in a specific decade"); 
    System.out.println("\t3. - Show what name had a specific rank for a certain decade"); 
    System.out.println("\t4. - Exit program"); 
    int opt = 0; 
    int option = getInt(input,"Enter number (1-4): ", 1, 4); 
    if (option == 1) { 
     opt = 1; 
    } 
    else if (option == 2) { 
     opt = 2; 
    } 
    else if (option == 3) { 
     opt = 3; 
    } 
    else { 
     opt = 4; 
    } 
    return opt; 
} 

我的问题是,我怎么能得到菜单'按钮后重置'重置'。例如,我选择1,程序执行该操作,完成后,它会再次显示选项菜单,直到按4来终止它。

1和4

+1

尝试从每个案例子块中删除菜单()调用。四是唯一一个不再叫它,这可能是为什么它打破了。 – markg 2014-11-22 02:14:38

+0

这只是使它运行一次@markg – Zero 2014-11-22 02:17:11

+0

也许这个链接可以帮助你:http://stackoverflow.com/a/17015039/2444047 – Splamy 2014-11-22 02:17:57

回答

2

一个简单的选择是声明一个布尔变量和例如,将switch包装在一个while循环中

Boolean quit = false; 
while (!quit)  //or do-while 
{ 
    int opt = menu(); 
    switch(opt) 
    { 
     //other cases... 
     case 4: 
      quit = true; 
    } 
} 

我不知道为什么你在每种情况下调用菜单。

+0

这对我工作谢谢! – Zero 2014-11-22 02:26:31

+0

不客气:-) – splrs 2014-11-22 02:27:53

1

之间我没有在Java代码,但尝试每一种情况下的最终指向回默认的情况下,我的代码getInt方法只返回一个int,这样当你的程序完成你的动作,它会默认回到菜单。

1

对于我的菜单,我总是将菜单选项和请求包装在do-while循环中。

do{ 
menu code... 
} while (menu() != 4); 
+0

这种有点但是当它运行一次时,它会在第二次运行时跳过该操作,等等。 – Zero 2014-11-22 02:21:52

+0

我的不好,在发布之前忽略了意识到这是java。用C++编码全学期上学。 – Spencer 2014-11-22 02:27:08

1

当按下4时,您可以保持代码无限循环并退出程序。 无需在您的所有情况下拨打menu(),因为您必须在每次迭代中仅显示一个菜单。

为了使一个无限循环使用

while(true) { 
    //some code 
} 

用于退出程序使用:

System.exit(0); 

试试这个:

while(true) { 
    int choice = menu(); 
    switch (choice) { 
     case 1: 
      System.out.println("Stub 1"); 

      break; 
     case 2: 
      System.out.println("Stub 2"); 

      break; 
     case 3: 
      System.out.println("Stub 3"); 

      break; 
     case 4: 
      System.out.println("Program Terminated"); 
      System.exit(0); // for terminating the program 

    } 

}