How to find out which variable is throwing an exception?

后端 未结 2 1031
萌比男神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!

提交回复
热议问题