繁体   English   中英

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

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

我正在使用Eclipse构建计算器而我遇到了麻烦,因为我需要输入2个值。 这是我的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");
        }

    }
}

}

这是我的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);

}

我尝试使用Double.parseDouble(window.textField.getText());

但那没用。 我怎样才能使它工作? 提前致谢。

首先,我认为您的程序设计存在一些问题。为什么不使用事件(按钮点击,按键击键等)来触发计算? 我没有看到这个程序中while循环的好处。

此外,正如一些人已经指出的那样,您的代码甚至在用户输入之前就从文本字段中读取和解析值。 这肯定会产生无效的结果。

尝试像(未测试)的东西:

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

您正在从TextField请求文本而不实际检查文本是否存在。 如果您想以这种方式循环,则必须首先查看是否输入了文本,然后将输入分配给double。 我会推荐一个不同的策略。

在我看来,你在这里使用循环的逻辑并不是最好的。 如果你必须从TextField中读取这两个数字,我实际上会添加一个KeyListener并等待输入键。 就像是

伪代码

...
// 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.
        }
    }
}

有用的网址

以下是KeyListeners的更多信息: http//docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

这是TextField上的链接以及如何使用它们: http//docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

这是你如何做到的:

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

你可以直接使用:

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

它是一个静态方法,返回参数中给出的任何内容的double值。

暂无
暂无

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

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