【问题标题】:How do I convert a JTextField string to a double?如何将 JTextField 字符串转换为双精度?
【发布时间】:2016-04-13 16:57:15
【问题描述】:

我的程序适用于生日和年龄。我在尝试将我的 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();

    }

}

【问题讨论】:

  • 你遇到了什么错误?
  • 您是否尝试打印txtMonth 来排除故障...?这应该是第一步......
  • 代码无法编译。

标签: java string double jtextfield


【解决方案1】:

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

尝试使用:

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

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

【讨论】:

    【解决方案2】:

    你可以试试:

        Double Amount = Double.valueOf(txtMonth);
    

    根据文档:

    此方法返回一个 Double 对象,该对象包含由参数 String 表示的双精度值。

    【讨论】:

      【解决方案3】:
       double Amount = Double.parseDouble(txtMonth.getText());
      

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

      parseDouble() 返回一个原始的double 值。 valueOf() 返回包装类Double 的一个实例。

      在 Java 5 引入自动装箱之前,这两者之间有一个非常显着的区别。

      【讨论】:

        【解决方案4】:

        您需要通过调用方法getText 来获取对象txtMonth 的文本,并且请验证输入或使用Try catch fall the input is not valid...

        示例:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-16
          • 1970-01-01
          • 2011-08-11
          • 1970-01-01
          相关资源
          最近更新 更多