如何将 JTextField 字符串转换为双精度字符串?

How do I convert a JTextField string to a double?

我的程序适用于生日和年龄。我在尝试将我的 JTextField 字符串转换为双打时遇到了麻烦。我使用了 parse 方法,但仍然收到错误。请帮忙!

public class MyPaymentFrame extends JFrame implements ActionListener {

    JTextField txtAge;
    JTextField txtDate;

        public MyPaymentFrame()  {
        Container mycnt = getContentPane();
        mycnt.setLayout(new FlowLayout());

        Color c = new Color(56, 100, 20);
        Font F = new Font("Arial", Font.ITALIC, 20);

        mycnt.add(new JLabel("Enter your Age"));
        txtAge = new JTextField(15);
        mycnt.add(txtAmount);


        mycnt.add(new JLabel("Enter birthdate"));
        txtDate = new JTextField(10);
        mycnt.add(txtDate);

    }
        if (e.getActionCommand().equals("Clear")) {
            txtAge.setText("");
            txtDate.setText("");
        }

        if (e.getActionCommand().equals("Calculate")) {
            // Converting String to Double
            double Amount = Double.parseDouble(txtMonth);

        }

    }
    public static void main(String[] args) {

        Theframe myframe = new Theframe();

    }

}

你可以试试:

    Double Amount = Double.valueOf(txtMonth);

根据文档:

此方法 returns 一个 Double 对象保存由参数 String 表示的双精度值。

显然 txtMonth 是一个 JTexfield,但 Double.parseDouble 方法接收一个字符串。检查方法的 javadoc here.

尝试使用:

double Amount = Double.parseDouble(txtMonth.getText());

此外,如果文本无法转换为双精度,此方法将抛出 NumberFormatException。

 double Amount = Double.parseDouble(txtMonth.getText());

Double Amount = Double.valueOf(txtMonth.getText());

parseDouble() returns 原始 double 值。 valueOf() returns 包装器实例 classDouble

在 Java5 引入自动装箱之前,这是两者之间非常显着的区别。

您需要通过调用方法 getText 获取对象 txtMonth 的文本,并且请验证输入或使用 Try catch 发现输入无效...

示例:

public static void main(String[] args) {
    double amount=0.0;
    try {
         amount = Double.parseDouble(txtMonth.getText());
    } catch (Exception e) {
        System.err.println("ups, this was not castable to double");
          amount=-10.0;
    }
    System.out.println("Here is the double: "+ amount);
}