简体   繁体   中英

How can I prevent my Java code from processing if there is a user-input error?

I am writing a temperature converter that uses a gui. I have it set up to if the user inputs a string or an invalid temperature, an error label appears under the input box. However, the code will still process as if the user inputted a 0. It will still output the conversions. How can I stop it from doing that in the class I have below?

package gui;
import javax.swing.*;
import java.awt.*;

public class JDataInput
    extends JPanel
{
    private JLabel lblInput;
    private JTextField txtInput;
    private JLabel lblMessage;

    public JDataInput()
    {

    }

    public JDataInput(String caption)
    {

        lblInput = new JLabel(caption);
        txtInput = new JTextField(20);
        lblMessage = new JLabel("");

        JPanel row1 = new JPanel();
        JPanel row2 = new JPanel();

        row1.add(lblInput);
        row1.add(txtInput);
        row2.add(lblMessage);

        this.add(row1);
        this.add(row2);

    }

    public double getDoubleValue()
    {
        double returnValue = 0;
        lblMessage.setText(" ");

        try
        {
            returnValue =   Double.parseDouble(txtInput.getText());

        }
        catch (NumberFormatException nfex)
        {
            lblMessage.setText(nfex.toString());
            lblMessage.setForeground(Color.RED);
        }
        return returnValue;
    }

    public double getIntValue()
    {
        int returnValue = 0;
        lblMessage.setText(" ");
        try
        {
            returnValue =   Integer.parseInt(txtInput.getText());
        }
        catch (NumberFormatException nfex)
        {
            lblMessage.setForeground(Color.RED);
            lblMessage.setText(nfex.toString());
        }
        return returnValue;
    }

}

return a null value from catch block eg

 public double getDoubleValue()
    {
        double returnValue = 0;
        lblMessage.setText(" ");

        try
        {
            returnValue =   Double.parseDouble(txtInput.getText());

        }
        catch (NumberFormatException nfex)
        {
            lblMessage.setText(nfex.toString());
            lblMessage.setForeground(Color.RED);
            return null;
        }
        return returnValue;
    }

this will exit from the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM