【发布时间】:2013-12-11 02:52:01
【问题描述】:
当调用此循环时,如果无限运行并显示捕获错误,用户甚至无需输入任何内容。我找不到任何原因。有什么建议吗?
public Purchase groceryStoreMenu(LemonadeStand lemonadeStand) {
boolean getMenu = true;
int userEnteredNumber = -1;
currentPurchase = new Purchase();
while(getMenu){
try{
System.out.println("Grocery Store");
System.out.printf("%s\t%s%n%s\t%s%n%s\t%s%n%s\t%s%n%s\t%s%n%s\t%s%n" , "1:" , "Buy lemons", "2:", "Buy cups" , "3:" , "Buy sugar" ,
"4:" , "Buy ice" , "5:" , "Done");
userEnteredNumber = reader.nextInt();
if (userEnteredNumber == 1 ) {
money = lemonadeStand.profit(0);
lemonsMenu(money);
}else if (userEnteredNumber == 2){
money = lemonadeStand.profit(0);
cupsMenu(money);
}else if (userEnteredNumber == 3){
money = lemonadeStand.profit(0);
sugarMenu(money);
}else if (userEnteredNumber == 4){
money = lemonadeStand.profit(0);
iceMenu(money);
}else if (userEnteredNumber == 5){
getMenu = false;
} else {
throw new Exception();
}
} catch(Exception e) {
System.out.println("Error in number format. Enter a valid number from the choices (1,2,3,4,5)");
}
}
return currentPurchase;
【问题讨论】:
-
您没有收到任何编译时错误吗?
-
我假设读者是扫描仪?看看这个:stackoverflow.com/questions/11643222/java-scanner-nextint
-
@user3053348 在下面查看我的答案
-
问题是你忽略了异常,如果你查看 e.getMessage() 你可能应该得到更多信息。
标签: java loops while-loop infinite-loop infinite