I’m a Begginer to Java and I’m trying to use JOptionPanes to input my Variables.
Whilst Trying to validate my input Variables I put the input statements in this while loop.
while (input==false)
{
inputNumberCoeffa=JOptionPane.showInputDialog("Enter co-efficient of X: ");
inputNumberConsta=JOptionPane.showInputDialog("Enter Constant Number: ");
inputNumberPowa=JOptionPane.showInputDialog("Enter Power Bracket should be raised to:");
if (inputNumberCoeffa==null
|| inputNumberConsta==null
|| inputNumberPowa==null
||inputNumberCoeffa.isEmpty()
|| inputNumberConsta.isEmpty()
|| inputNumberPowa.isEmpty()
|| inputNumberCoeffa.matches("[A-Za-z]*")
|| inputNumberConsta.matches("[A-Za-z]*")
|| inputNumberPowa.matches("[A-Za-z]*"))
{
JOptionPane.showMessageDialog(null,"Please Enter a Number");
}
else
{
input=true;
}
double inputNumberCoeff=Double.parseDouble(inputNumberCoeffa);
double inputNumberConst=Double.parseDouble(inputNumberConsta);
double inputNumberPow=Double.parseDouble(inputNumberPowa);
}
This while loop was made to protect the parseDouble Statements at the Bottom from bad data. However to display the error message you have to enter in each point of Data. I could put a While loop around each Data entry point but I would Like to know is there a more efficient way that this question can be resolved?
Take a look at the Dialog Tutorial.
Something that you can do is create a class that validates input and implement
KeyListenerand then createJOptionPanes and calladdKeyListener()and pass it your listener. So as the user types things into your JOptionPane, you can filter what is being typed (and set the property as “0” or something if they hit Enter without typing anything). You can also add additional listeners (see also: PropertyChangeListener) if you need other events to be handled.