You don't check if the user's input can be parsed to double
, which will cause an exception when you parse. To check if your input is numerical, you can use the following function, which uses a regex :
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
This example comes from this SO's answerSO's answer
This way, you can validate your input instead of letting the application crash if I enter non-numerical characters as an input (note that this regex will accept "." and "-" as valid characters).
You need to loop on your input until it is valid, so you could do something like this :
String carCost = JOptionPane.showInputDialog("What is the total cost of the car?");
while(!isNumeric(carCost)){
carCost = JOptionPane.showInputDialog("Please enter a valid car cost : ");
}
Afterwards, you could extract this logic into a method, let's call it getDoubleInput(String paneText, String invalidInputText)
private String getDoubleInput(String paneText, String invalidInputText){
String input = JOptionPane.showInputDialog(paneText);
while(!isNumeric(input)){
input = JOptionPane.showInputDialog(invalidInputText);
}
return input;
}
Then you could, as @Caridorc's pointed, skip the String
variable in your code and use this format :
double carCost = Double.parseDouble(getDoubleInput("What is the total cost of the car?","Please enter a valid car cost : "));
double insCostP = Double.parseDouble(getDoubleInput("What is the yearly cost of the insurance?", "Please enter a valid yearly cost of insurance : "));
//...
If you dislike have 2 String
parameter to the method, you could use a generic invalid input message such as : "Please enter a valid input : ". Then the method would look like this :
private String getDoubleInput(String paneText){
String input = JOptionPane.showInputDialog(paneText);
while(!isNumeric(input)){
input = JOptionPane.showInputDialog("Please enter a valid input : ");
}
return input;
}
You wouldn't need the second parameter in the method call :
double carCost = Double.parseDouble(getDoubleInput("What is the total cost of the car?"));