简体   繁体   English

如何从TextField获取用户输入并将其转换为Double?

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

I'm using Eclipse to build a calculator and I am having trouble because I need to have 2 values entered by the user. 我正在使用Eclipse构建计算器而我遇到了麻烦,因为我需要输入2个值。 Here is my code for the run class. 这是我的run类的代码。

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: 这是我的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()); 我尝试使用Double.parseDouble(window.textField.getText());

but that didn't work. 但那没用。 How can I make it work? 我怎样才能使它工作? Thanks in advance. 提前致谢。

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. 我没有看到这个程序中while循环的好处。

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());
    ...
}

You are requesting text from the TextField without actually checking if the text is there. 您正在从TextField请求文本而不实际检查文本是否存在。 If you would like to loop this way you must first see if there is text entered, then assign the input to the double. 如果您想以这种方式循环,则必须首先查看是否输入了文本,然后将输入分配给double。 I would recommend a different strategy though. 我会推荐一个不同的策略。

Your logic of using a loop here is not the best in my opinion. 在我看来,你在这里使用循环的逻辑并不是最好的。 If you must read both numbers from the TextField I would actually add a KeyListener and await for the enter key. 如果你必须从TextField中读取这两个数字,我实际上会添加一个KeyListener并等待输入键。 Something like 就像是

PSEUDO-CODE 伪代码

...
// global vals
double a = Null;
double b = Null;
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
        if (!window.textField.getText().equals("")) {
            // check if input is a legal double value
            // notify user that you recieved the first number
            // and request the next input.
            // once both inputs have been entered do your calculation and 
            // output the result. The program will continue to respond to key triggers.
        }
    }
}

HELPFUL LINKS 有用的网址

Here is some more info on KeyListeners: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html 以下是KeyListeners的更多信息: http//docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

Here is a link on TextField and how to use them: http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html 这是TextField上的链接以及如何使用它们: http//docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

这是你如何做到的:

double value=Double.parseDouble(jtextfield-name.getText());

You can directly use: 你可以直接使用:

Double.valueOf("Pass your string here");

It is a static method that returns double value of whatever being given in the arguments. 它是一个静态方法,返回参数中给出的任何内容的double值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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