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...
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
}
}
}
You need something like:
double input2;
try{
//read input2
}catch( ... ){
//... log AND assign a value to input2 in case of invalid input
}
return input2;
Let your method throw an exception or return nan.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With