How to find out which variable is throwing an exception?

后端 未结 2 1032
萌比男神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:48

    There are various simple ways to get there:

    1. Call hasNextXxx() prior calling nextXxx().
    2. If you go for one try/catch block per input, it is very clear within your catch block which variable caused the problem (you could then call a generic method with a specific error message to avoid code duplication)
    3. You could use reference types for your variables; if you use Double / Integer instead of double / int ... you could check which of the two variables is still null
    4. You put in a little boolean variable, like billAmountIsValid. Initially that variable is false, you turn it to true after the call to nextDouble(). Then you can easily check in your try block whether you got a valid billAmount.

    After some more thinking: you really want a combination of 1 + 2: you see; when the users enters a correct billAmount; why would you want to forget about that value when the second value gives a bad second value? No - you should be looping for each variable, until you receive a valid input. And only then you start asking for the next value!

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题