Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java try/catch - either "return isn't found" or "variable isn't initialized"?

I've been staring at this for hours and unable to think of a solution; I usually handle validation of this type with regex but am trying to use a built-in solution for a change (obviously, I don't do this frequently):

private static double promptUserDecimal(){
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a decimal");
    try{
        double input2 = Double.parseDouble(scan.nextLine());
        return input2;
    } catch(NumberFormatException e){
        System.out.println("Sorry, you provided an invalid option, please try again.");
    }
}

The error with this is that the "return" isn't found by the compiler so I get a compile error. If I put the "return" outside of the try/catch I need to declare/initialize "input2" which defeats the purpose of the operation. Any assistance is appreciated...

like image 822
sfell77 Avatar asked Oct 07 '12 22:10

sfell77


4 Answers

If you want the user to "please try again", it sounds like you need a loop:

private static double promptUserDecimal(){
    final Scanner scan = new Scanner(System.in);

    // Ask for input until we get something valid
    while (true) {  // Terminated by return within
        System.out.println("Enter a decimal");
        try {
            return Double.parseDouble(scan.nextLine());
        } catch(NumberFormatException e){
            System.out.println("Sorry, you provided an invalid option, please try again.");
            // No return, so the loop will run again
        }
    }
}
like image 150
Wyzard Avatar answered Oct 27 '22 21:10

Wyzard


You need something like:

double input2;
try{
  //read input2
}catch( ... ){
  //... log AND assign a value to input2 in case of invalid input
}
return input2;
like image 41
dan Avatar answered Oct 27 '22 20:10

dan


Let your method throw an exception or return nan.

like image 25
Tobias Ritzau Avatar answered Oct 27 '22 20:10

Tobias Ritzau


Throw an exception in the catch section. Wherever you call the promptUserDecimal method, catch any exception and print the message there:

public static void main(String[] args) {

    double d = 0.0;
    while (double == 0) {
        try {
            d = promptUserDecimal();
        } catch (NumberFormatException e) {
            //log the message...
            d = 0.0;
        }
    }
}

private static double promptUserDecimal() throws NumberFormatException {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a decimal");
    return Double.parseDouble(scan.nextLine());
}

This would be a better approach because you let the promptUserDecimal cares only about handling reading a double value. You must try to tend to separate each class and method for the specific purpose it was designed for.

like image 34
Luiggi Mendoza Avatar answered Oct 27 '22 22:10

Luiggi Mendoza