add data validation

I have the following code for a future value calculator:

I need to add data validation so that the user must enter data in all three fields:  can someone please get me started adding the validation code?


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;



public class FutureValueApp
{
    public static void main(String[] args)
    {
        JFrame frame = new FutureValueFrame();
        frame.setVisible(true);
    }
}

class FutureValueFrame extends JFrame
{
    public FutureValueFrame()
    {
        setTitle("Future Value Calculator");
        centerWindow(this);
        setSize(267, 200);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new FutureValuePanel();
        this.add(panel);
    }

    private void centerWindow(Window w)
    {
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d = tk.getScreenSize();
        setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    }
}

class FutureValuePanel extends JPanel implements ActionListener
{
    private JTextField  paymentTextField,
                        rateTextField,
                        yearsTextField,
                        futureValueTextField;
    private JLabel      paymentLabel,
                        rateLabel,
                        yearsLabel,
                        futureValueLabel;
    private JButton     calculateButton,
                        exitButton;

    public FutureValuePanel()
    {
        // display panel
        JPanel displayPanel = new JPanel();
        displayPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        // payment label
        paymentLabel = new JLabel("Monthly Payment:");
        displayPanel.add(paymentLabel);

        // payment text field
        paymentTextField = new JTextField(10);
        displayPanel.add(paymentTextField);

        // rate label
        rateLabel = new JLabel("Yearly Interest Rate:");
        displayPanel.add(rateLabel);

        // rate text field
        rateTextField = new JTextField(10);
        displayPanel.add(rateTextField);

        // years label
        yearsLabel = new JLabel("Number of Years:");
        displayPanel.add(yearsLabel);

        // years text field
        yearsTextField = new JTextField(10);
        displayPanel.add(yearsTextField);

        // future value label
        futureValueLabel = new JLabel("Future Value:");
        displayPanel.add(futureValueLabel);

        // future value text field
        futureValueTextField = new JTextField(10);
        futureValueTextField.setEditable(false);
        futureValueTextField.setFocusable(false);
        displayPanel.add(futureValueTextField);

        // button panel
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        // calculate button
        calculateButton = new JButton("Calculate");
        calculateButton.addActionListener(this);
        buttonPanel.add(calculateButton);

        // exit button
        exitButton = new JButton("Exit");
        exitButton.addActionListener(this);
        buttonPanel.add(exitButton);

        // add panels to main panel
        this.setLayout(new BorderLayout());
        this.add(displayPanel, BorderLayout.CENTER);
        this.add(buttonPanel, BorderLayout.SOUTH);
    }


    public void actionPerformed(ActionEvent e)
    {
        Object source = e.getSource();
        if (source == exitButton)
            System.exit(0);
        else if (source == calculateButton)
        {
            double payment = Double.parseDouble(paymentTextField.getText());
            double rate = Double.parseDouble(rateTextField.getText());
            int years = Integer.parseInt(yearsTextField.getText());
            double futureValue = FinancialCalculations.calculateFutureValue(
                payment, rate, years);
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            futureValueTextField.setText(currency.format(futureValue));
        }


            }

             }
edthatcherAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:


Immediately ffter this code

   else if (source == calculateButton)
        {

you can insert check:

if(paymentTextField.getText().trim().length() == 0 || rateTextField.getText().trim().length() == 0 || yearsTextField.getText().trim().length() == 0){
System.out.println("Error : you need to fill in all three fileds!");

}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
for_yanCommented:

this ...trim().length() == 0

ensures that even if folks type some spaces in the field that will not be passing .


It would be better to do better chacek, because they
should enter strings which should evaluate to double ot int
thewre for you want  to have more accurate check
which would make sure that they put not just something but something which can be evaluate as numbers




for_yanCommented:

I think it would be good idea to replace this code :
------------------------------
 double payment = Double.parseDouble(paymentTextField.getText());
            double rate = Double.parseDouble(rateTextField.getText());
            int years = Integer.parseInt(yearsTextField.getText());
----------------------------------

with this code:
--------------------------------------------------------------
 double payment = 0.0;
            double rate = 0.0;
            int years = 0;
try {
payment = Double.parseDouble(paymentTextField.getText());
             rate = Double.parseDouble(rateTextField.getText());
             years = Integer.parseInt(yearsTextField.getText());
} catch (Exception ex) {
System.out.println("Not a number in one of the textfileds - try again!");
return;
}

-------------------------------------------------

I guess this change will cover the case with empty fields either,
as empty string will not evaluate to a number - but you may want to
check this my statement



CEHJCommented:
Change your code to
if (source == exitButton) {
            System.exit(0);
        } else if (source == calculateButton) {
            try {
                double payment = Double.parseDouble(paymentTextField.getText()
                                                                    .trim());
                double rate = Double.parseDouble(rateTextField.getText().trim());
                int years = Integer.parseInt(yearsTextField.getText().trim());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null,
                    "Please ensure all three fields have valid numbers");

                return;
            }

            double futureValue = FinancialCalculations.calculateFutureValue(payment,
                    rate, years);
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            futureValueTextField.setText(currency.format(futureValue));
        }

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.