Niddog
Niddog

Reputation: 7

How do you Reset a While Loop without Breaking it in Java?

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?

Upvotes: 0

Views: 219

Answers (2)

Jon Lin
Jon Lin

Reputation: 143906

Take a look at the Dialog Tutorial.

Something that you can do is create a class that validates input and implement KeyListener and then create JOptionPanes and call addKeyListener() 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.

Upvotes: 2

Andrea Sindico
Andrea Sindico

Reputation: 7440

create a method that returns a double and contains the while loop plus all the required checks plus the parse double statement and use that to set your inputNumberXXX variables. In this way you won't have to copy and paste the code three times because you will just invoke three times the same method.

Upvotes: 1

Related Questions