2016-04-13 154 views
0

我的程序適用於生日和年齡。我嘗試將我的JTextField字符串轉換爲雙打時遇到問題。我使用瞭解析方法,但仍然收到錯誤。請幫忙!如何將JTextField字符串轉換爲雙精度?

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

    } 

} 
+0

你遇到了什麼錯誤? – robotlos

+0

您是否嘗試打印'txtMonth'來排除故障......?它應該是第一步.... – Maljam

+0

代碼不能編譯。 – null

回答

0

顯然txtMonth是一個JTexfield,但Double.parseDouble方法接收一個字符串。檢查方法的javadoc here

嘗試使用:

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

而且,這種方法將拋出NumberFormatException如果該文本不能轉換爲double。

0

你可以嘗試:

Double Amount = Double.valueOf(txtMonth); 

根據文檔:

該方法返回一個Double對象持有的論點String表示的double值。

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

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

parseDouble()返回一個原語double值。 valueOf()返回包裝類Double的一個實例。

在Java 5引入自動裝箱之前,這是兩者之間非常顯着的區別。

0

你需要通過調用方法getText獲取對象txtMonth的文本並請驗證輸入或使用嘗試捕捉落在輸入無效...

例子:

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); 
} 
相關問題