[英]How can I convert input from JTextField into double. Input value is from user
我正在嘗試使用JTextField的輸入並將其轉換為雙行,因為我要在程序中的數學公式中使用該輸入..但是當我嘗試運行代碼時,它給出了一個錯誤..我認為我解析的方法有誤。任何幫助嗎? 謝謝!
xLabel = new JLabel("Subject");
xTF = new JTextField(4);
xTF.addKeyListener(new KeyHandler());
xString = xTF.getText();
xDouble = Double.parseDouble(xString);
KeyListener
,使用DocumentFilter
,更多信息請看實現文檔過濾器和DocumentFilter示例 InputVerifier
。 有關更多詳細信息,請參見驗證輸入 。 JFormmattedField
或JSpinner
。 有關更多詳細信息,請參見如何使用格式化的文本字段和如何使用微調框 。 很難說,但是請記住,您是在事件驅動的環境中進行操作的,除非用戶執行了某些操作,否則您不應該嘗試獲取字段的值
通過在字符串上使用trim()刪除任何可用的空格
xDouble = Double.parseDouble(xString.trim());
我假設xString是有效字符串,而xDouble是Double類型
您應該使用parseDouble(String s)
和相關的異常是NumberFormatException
java.lang.Double.parseDouble()方法返回一個新的double,該double初始化為指定的String表示的值,如Double類的valueOf方法所做的那樣。
例如:
public class Main {
public static void main(String[] args) {
String str = "50.00001";
double retval =Double.parseDouble(str);
System.out.println("Value = " + retval);
}
}
看起來不錯,在測試之前是否在文本字段中輸入了正確的值? 例如,如果您將其保留為空或輸入“ 1,3”,則可能不會接受。
編輯:我剛剛做了一個測試,正如我所說,它只接受這樣的值:“ 1.3”
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class MyApp extends JFrame implements ActionListener {
JTextField textField;
JLabel label;
JButton okButton;
public MyApp() {
textField = new JTextField(4);
label = new JLabel("N/A");
okButton = new JButton("Ok");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
add(textField, BorderLayout.NORTH);
add(label, BorderLayout.CENTER);
add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(this);
pack();
}
public static void main(String[] args) {
MyApp app = new MyApp();
app.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == okButton) {
double d = 0;
d = Double.parseDouble(textField.getText());
label.setText(String.valueOf(d));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.