变量不会引发异常,而是对变量赋值的右侧进行评估,因此在异常中没有任何信息可以说明将成功赋给哪个变量。
您可以考虑使用一种包含提示消息和重试的新方法:
billAmount = doubleFromUser(sc, "What is the bill? ", "bill");
哪里
doubleFromUser是:
static double doubleFromUser(Scanner sc, String prompt, String description){ while(true) { //until there is a successful input try { System.out.print(prompt); //move to before the loop if you do not want this repeated return sc.nextDouble(); } catch (InputMismatchException e1) { System.out.println("Please enter a valid number for the " + description); } }}对于int和double,您将需要一个不同的变量,但是如果您有更多的提示,从长远来看,您将可以节省。



