对于情况“ 1”,它似乎只是循环而不是跳转到drunkSong();
。如果用户选择大小写为“ 2”,它将正常工作,并要求用户输入数字以返回整数“ BeerNum”。
案例“ 1”需要接受默认值99,而案例“ 2”需要接受用户输入。
如果您可以指出我的错误或出了问题的地方,则我已附加了代码。
package PartOne;
import java.util.Scanner;
public class View {
public void begin() {
BeerSong.drunkSong();
}
private int setBeerNum() {
return beerNum;
}
private int beerNum;
public Integer Menu() {
Scanner in = new Scanner(System.in);
// print menu
for (int i = 1; i <= 3; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
// handle user commands
boolean quit = false;
int menuItem;
do {
System.out.print("Choose menu item: ");
menuItem = in.nextInt();
switch (menuItem) {
case 1:
System.out.println("Default ");
begin();
while (true)
try {
//where I have made a mistake
beerNum = 99;
this.beerNum = setBeerNum();
break;
} catch (NumberFormatException BecauseIsaidSo) {
System.out.print("Try again: ");
}
//working
case 2:
System.out.println("Enter your number to play the song: ");
Scanner scan = new Scanner(System.in);
while (true)
try {
beerNum = Integer.parseInt(scan.nextLine());
this.beerNum = setBeerNum();
return beerNum;
} catch (NumberFormatException BecauseIsaidSo) {
System.out.print("Try again: ");
}
case 0:
quit = true;
break;
default:
System.out.println("Invalid choice.");
}
}
while (!quit) ;
System.out.println("Bye-bye!");
return null;
}
}
答案 0 :(得分:0)
我认为最好将菜单逻辑封装在单独的类中,然后将所有逻辑封装在其中。此外,每个菜单项的逻辑也应封装在单独的方法中。
public final class Menu {
private Integer res;
private boolean quit;
public static Integer showMenuAndGetResult() {
Menu menu = new Menu();
menu.activate();
return menu.res;
}
private Menu() {
}
private void activate() {
try (Scanner in = new Scanner(System.in)) {
show();
while (!quit) {
System.out.print("Choose menu item: ");
int menuItem = in.nextInt();
if (menuItem == 1)
onMenuItem1(in);
else if (menuItem == 2)
onMenuItem2(in);
else if (menuItem == 0)
onMenuQuit();
else
System.out.println("Invalid choice.");
}
System.out.println("Bye-bye!");
}
}
private void show() {
for (int i = 1; i <= 3; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
System.out.println();
}
private void onMenuItem1(Scanner scan) {
System.out.println("Default ");
// TODO menu 1 logic incapsulation
}
private void onMenuItem2(Scanner scan) {
System.out.println("Enter your number to play the song: ");
// TODO menu 2 logic incapsulation
}
private void onMenuQuit() {
res = null;
quit = true;
}
}
PS 。我个人尝试避免使用switch
。请注意,这不是我的建议。我认为if ... else if更易读和没有问题。