How to find out which variable is throwing an exception?

后端 未结 2 1034
萌比男神i
萌比男神i 2021-01-24 05:04

I\'m writing a program that culculates tip and total from bill and tip rate.

public void takeUserInput() {
    Scanner sc = new Scanner(System.in);    
    doubl         


        
2条回答
  •  悲哀的现实
    2021-01-24 05:58

    The variable isn't throwing the exception, the evaluation of the right hand side of the variable assignment is, and so there is no information in the exception to say which variable it was about to assign that to had it succeeded.

    What you could consider instead is a new method that encompasses the prompting messages and retries:

    billAmount = doubleFromUser(sc, "What is the bill? ", "bill");
    

    Where doubleFromUser is:

    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);
            }
        }
    }
    

    You will need a different one for int and double, but if you have more prompts, you will save in the long run.

提交回复
热议问题