java简单UI循环,找不到bug
我在下面编写了UI类,它基本上只是一个简单的循环,调用类中的两个方法,即基于控制台的UI
用户应该能够从6个菜单选项中选择一个。现在,来自用户的选择输入必须是int类型。我用try{}catch{}包围了选择代码,以处理无效的非int输入
所以当我测试它时,一切正常。现在,如果用户输入了一个有效的选择,int值为1、2、3、4、5或0,那么它就卡在while循环中。这不是错误,我只是还没有实现菜单选项
当用户输入非int无效输入时,会出现错误。也许我在异常处理方面做了一些奇怪的事情,不确定,但若你们输入了一个无效的输入,它就会无休止地循环,就像一个无效的输入被反复输入一样,即使我什么也没输入。它似乎是从其他地方获取输入,但我不知道是什么将输入发送到扫描仪
我知道我还有其他的Scanner对象,但它们甚至不在同一个类中,并且还没有连接到这个类。我希望其他人能看看,也许能告诉我我做错了什么
class UI{
private Scanner userInput;
private String fileName;
private Performance perf;
private Menu menu;
private int selection = -1;
public UI(){
userInput = new Scanner(System.in);
setFileName();
initializePerformance();
initializeMenu();
loopUI();
}
void setFileName() {
System.out.print("\nEnter the performance file name: ");
try{
fileName = userInput.next();
} catch (Exception e){
System.err.println(e.getMessage());
setFileName();
}
}
void initializePerformance(){
perf = new Performance(fileName);
}
void initializeMenu(){
this.menu = new Menu();
menu.addItem("Rows");
menu.addItem("Show Row");
menu.addItem("Seat Status");
menu.addItem("Buy Ticket");
menu.addItem("Return Ticket");
menu.addItem("Exit and Save");
}
void showMenu(){
menu.showMenu();
}
void selection() {
System.out.println("\nSelection[1,2,3,4,5,0]: ");
try{
this.selection = userInput.nextInt();
}catch(Exception e){
System.out.println("Invalid selection, try again.");
}
}
void loopUI(){
while(selection != 0){
System.out.println("\n" + perf.getName());
showMenu();
selection();
}
}
}
# 1 楼答案
您必须在catch子句中添加
userInput.next()
,以便在使用userInput.nextInt()
之后使用该行的其余部分