将JTextfield字符串解析为整数 [英] Parsing JTextfield String into Integer
问题描述
因此,我可以将String
从JTextField
转换为int
.它说Exception in thread "main" java.lang.NumberFormatException: For input string: ""
.请帮忙.
So I have this to convert String
from JTextField
to int
. It says Exception in thread "main" java.lang.NumberFormatException: For input string: ""
. Please help.
JTextField amountfld = new JTextField(15);
gbc.gridx = 1; // Probably not affecting anything
gbc.gridy = 3; //
add(amountfld, gbc);
String amountString = amountfld.getText();
int amount = Integer.parseInt(amountString);
推荐答案
来自
抛出:NumberFormatException-如果字符串不包含
可解析的整数.
Throws: NumberFormatException - if the string does not contain a
parsable integer. 空字符串 The empty String 有很多方法可以避免这种情况.您可以简单地检查从 There are many ways in which you can avoid this. You can simply check if the 现在使用方便的 Now create a 现在,您无需进行任何检查就可以从 Now you can retrieve the integer value from 这篇关于将JTextfield字符串解析为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
""
不是可解析的整数,因此,如果未输入任何值,您的代码将始终生成NumberFormatException
.""
is not a parsable integer, so your code will always produce a NumberFormatException
if no value is entered.amountField.getText()
获得的String
值是否确实被填充.您可以创建一个自定义IntegerField
,该自定义IntegerField
仅允许输入整数,但添加String
value you got from amountField.getText()
is actually populated. You can create a custom IntegerField
, which only allows integers as input, but adding Document to a JTextField
. Create a Document to only allow integers an input:public static class IntegerDocument extends PlainDocument {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
StringBuilder sb = new StringBuilder(str.length());
for (char c:str.toCharArray()) {
if (!Character.isDigit(c)) {
sb.append(c);
}
}
super.insertString(offs, sb.toString(), a);
}
}
getInt
方法创建一个IntergerField
,如果未输入任何内容,该方法将返回零:IntergerField
with a convenient getInt
method, which returns zero if nothing is entered:public static class IntegerField extends JTextField {
public IntegerField(String txt) {
super(txt);
setDocument(new IntegerDocument());
}
public int getInt() {
return this.getText().equals("") ? 0 : Integer.parseInt(this.getText());
}
}
amountField
检索整数值:amountField
without doing any checks:JTextField amountField = new IntegerField("15");
...
//amount will be zero if nothing is entered
int amount = amountField.getInt();