If a NumberFormatException
is thrown when I parse a double from a string (given by the user), how can I retry?
String input = JOptionPane.showInputDialog(null, message + count);
double inputInteger = Double.parseDouble(input);
If a NumberFormatException
is thrown when I parse a double from a string (given by the user), how can I retry?
String input = JOptionPane.showInputDialog(null, message + count);
double inputInteger = Double.parseDouble(input);
inputInteger = null;
while(inputInteger == null)
{
input = JOptionPane.showInputDialog(null, message + count);
try
{
if (isValidGrade(input, maxPoints))
inputInteger = Double.parseDouble(input);
}
catch(NumberFormatException e)
{
// Show your error here
inputInteger = null;
}
}
You need to wrap your code in try catch and handle the exception to do whatever you want. Do sth like this:
try {
inputInteger = Double.parseDouble(input);
}catch(NumberFormatException nfe) {
// Go to take input again
}
You can do this by calling the method recursively in the catch block. For an example:
public void yourMethod() {
try {
input = JOptionPane.showInputDialog(null, message + count);
if (isValidGrade(input, maxPoints)){
inputInteger = Double.parseDouble(input);
} catch (NumberFormatException e) {
this.yourMethod();
}
}
This is not a working code but use the concept in your code. Using a while loop is also another option. But I prefer this method over a while loop because this reduces the memory overhead.
You can use a do-while
loop to repeat the things in this case and make boolean variable false when all conditions are met.
Here is an example:
boolean isFailure=true;
do{
try{
input = JOptionPane.showInputDialog(null, message + count);
// do whatever you want....here...
isFailure=false;
}catch(NumerFormatException e){
//log the exception and report the error
JOptionPane.showMessageDialog(null,"Invalid Input! Try again!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}while(isFailure);