如何找出哪个变量抛出exception?

我正在编写一个程序,根据账单和小费率计算小费和总额。

public void takeUserInput() { Scanner sc = new Scanner(System.in); double billAmount; int tipRate; try { System.out.print("What is the bill? "); billAmount = sc.nextDouble(); System.out.print("What is the tip percentage? "); tipRate = sc.nextInt(); tc.calculate(billAmount, tipRate); } catch (InputMismatchException e1) { String errorMessage = "Please enter a valid number for the "; // errorMessage += billAmount or // errorMessage += tipRate ? } 

我正在寻找一种方法来找出哪个变量抛出InputMismatchException,所以我可以将哪个变量名添加到变量errorMessage中并打印到屏幕上。

变量不抛出exception,对变量赋值的右侧进行评估,因此exception中没有信息说明它要将哪个变量分配给它成功。

您可以考虑的是一种包含提示消息和重试的新方法:

 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,但是如果你有更多的提示,你将从长远来看保存。

有各种简单的方法可以达到目的:

  1. 在调用nextXxx()之前调用hasNextXxx()
  2. 如果你为每个输入选择一个 try / catch块,那么在catch块中很明显哪个变量导致了问题(然后你可以调用带有特定错误消息的generics方法来避免代码重复)
  3. 您可以为变量使用引用类型; 如果你使用Double / Integer而不是double / int …你可以检查两个变量中的哪一个仍为null
  4. 你输入了一个布尔变量,比如billAmountIsValid 。 最初该变量为false,在调用nextDouble()之后将其变为true。 然后,您可以轻松检查您的try块是否有有效的billAmount。

经过多思考后:你真的想要1 + 2的组合:你看; 当用户输入正确的billAmount时; 当第二个值给出错误的第二个值时,为什么要忘记该值? 否 – 您应该为每个变量循环 ,直到您收到有效输入。 只有这样你才开始要求下一个价值!