How Do I Get User Input from a TextField and Convert it to a Double?

13,809

First of all I think there are some issues with your design of the program.Why not use events (button clicks, keystrokes pressed etc) to trigger the calculations? I do not see the benefit of the while loop in this program.

Also, as some folks have already pointed out, your code is reading and parsing values from textfield even before user input. That surely will yield an invalid results.

Try something like (not tested):

calcButton = new JButton("Calculate");
calcButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent Ev) {
        actionCalc();
    }
});


public void actionCalc(){
    // get the string
    // validate string (check for empty string etc)
    // parse to Double
    Double val = Double.parseDouble(window.textField.getText());
    ...
}
Share:
13,809
stonkilla4
Author by

stonkilla4

Updated on June 12, 2022

Comments

  • stonkilla4
    stonkilla4 almost 2 years

    I'm using Eclipse to build a calculator and I am having trouble because I need to have 2 values entered by the user. Here is my code for the run class.

    import display.Gui;
    
    public class Main {
    
    public static void main(String argsp[]) {
    
        Gui window = new Gui();
        double a = 0, b = 0, c = 0;
        String operator;
        boolean calculate = true;
    
        window.setVisible(true);
        window.setSize(500, 400);
        window.setResizable(false);
        window.setLocationRelativeTo(null);
    
        while (calculate) {
            window.textArea_1.append("Enter an equation.\n");
            a = Double.parseDouble(window.textField.getText());
            operator = window.textField.getText();
            b = Double.parseDouble(window.textField.getText());
    
            if (operator.contains("+"))
                c = a + b;
    
            if (operator.contains("-"))
                c = a - b;
    
            if (operator.contains("*"))
                c = a * b;
    
            if (operator.contains("/"))
                c = a / b;
    
            if (operator.contains("x^2"))
                c = a * a;
    
            if (operator.contains("sqrt"))
                c = Math.sqrt(a);
    
            if (operator.contains("%"))
                c = a / 100;
    
            window.textArea.append("" + c + "\n");
            window.textArea.append("");
            window.textArea.append("Would you like to make another calculation? [Yes/No]\n");
    
            String calculation = window.textField.getText();
    
            try {
            if (calculation.equalsIgnoreCase("Yes"))
                calculate = true;
    
            if (calculation.equalsIgnoreCase("No"))
                calculate = false;
            } catch (Exception e) {
                window.textArea_1.append("Please enter yes or no");
            }
    
        }
    }
    
    }
    

    and here is my class for the JFrame:

    import java.awt.Dimension;
    import java.awt.EventQueue;
    
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    
    public class Gui extends JFrame {
    
    public JTextArea textArea, textArea_1;
    public JTextField textField;
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Gui frame = new Gui();
                    frame.setVisible(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    /**
     * Create the frame.
     */
    public Gui() {
        setBounds(100, 100, 450, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout(0, 0));
    
        textField = new JTextField();
        textField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent Ev) {
                textArea.append(textField.getText() + "\n");
                textField.setText("");
            }
        });
        textField.requestFocus();
        getContentPane().add(textField, BorderLayout.SOUTH);
        textField.setColumns(10);
    
        textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setPreferredSize(new Dimension(215, 200));
        getContentPane().add(textArea, BorderLayout.WEST);
    
        textArea_1 = new JTextArea();
        textArea_1.setEditable(false);
        textArea_1.setPreferredSize(new Dimension(215, 200));
        getContentPane().add(textArea_1, BorderLayout.EAST);
    
    }
    

    i tried using Double.parseDouble(window.textField.getText());

    but that didn't work. How can I make it work? Thanks in advance.