[英]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);
根據文檔:
此方法返回一個Double
對象,該對象保存參數String
表示的double值。
顯然txtMonth是一個JTexfield,但是Double.parseDouble方法接收一個String。 在此處檢查方法的javadoc。
嘗試使用:
double Amount = Double.parseDouble(txtMonth.getText());
另外,如果文本不能轉換為雙精度型,則此方法將引發NumberFormatException。
double Amount = Double.parseDouble(txtMonth.getText());
要么
Double Amount = Double.valueOf(txtMonth.getText());
parseDouble()
返回原始double
parseDouble()
值。 valueOf()
返回包裝類Double
的實例。
在Java 5引入自動裝箱之前,這是兩者之間非常重要的區別。
您需要通過調用方法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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.