[英]How do i make a check for in the input is a number or not in swing?
因此,我正在制作一個用戶在其中輸入輸入的應用程序,當他單擊按鈕時它會執行命令,但是輸入必須是整數,所以我添加了一個檢查,但是即使我輸入整數也給我一個錯誤說“您只能輸入數字!”
這是我的代碼:
String itemId = textField1.getText();
String itemAmount = textField2.getText();
int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);
if (!Double.isNaN(id) || !Double.isNaN(amount)){
JOptionPane.showMessageDialog(
null, "You can only enter numbers!"
);
即使在textFields中輸入數字后,我仍然無法通過此測試,為什么以及如何解決此問題? 謝謝。
但是輸入必須是整數,所以我加了一個檢查,但是即使輸入整數也給我一個錯誤,說“您只能輸入數字!”
有兩種使用方法
帶有數字格式化程序的JFormattedTextField,帶有SpinnerNumberModel的JSpinner
將DocumentFilter添加到JTextField
實際上,您可以這樣做:
String itemId = textField1.getText();
String itemAmount = textField2.getText();
int id;
int amount;
try{
id = Integer.parseInt(itemId);
amount = Integer.parseInt(itemAmount);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "You can only enter numbers!");
}
如果itemID
和itemAmount
值不可解析,則表示輸入了非數字
Double.isNaN(id)
如果指定的數字是非數字(NaN)值,則返回true,否則返回false。
但是您的id
和amout
是Integers,因此它將返回false,然后執行!Double.isNaN(id)
並將布爾值取反,因此結果為true。 這只是一個邏輯故障。 刪除!
。
if (Double.isNaN(id) || Double.isNaN(amount)){
JOptionPane.showMessageDialog(null, "You can only enter numbers!");
}
注意:
int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);
用try and catch塊對這兩行進行環繞,否則,如果輸入不是數字,則將收到NumberFormatException
。
try
{
int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);+
}catch(NumberFormatException e)
{
//print your error here
}
如果您不想使用JFormattedTextField,請使用Apache的StringUtils.isNumeric()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.