java.lang.NumberFormatException:对于输入字符串:“”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3701520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:39:46  来源:igfitidea点击:

java.lang.NumberFormatException: For input string: ""

javajtextfieldnumber-formatting

提问by Jessy

When running this code:

运行此代码时:

JTextField ansTxt;
...
ansTxt = new JTextField(5);
String aString = ansTxt.getText();
int aInt = Integer.parseInt(aString);

Why do I get this error?

为什么我会收到这个错误?

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

线程“AWT-EventQueue-0”中的异常java.lang.NumberFormatException:对于输入字符串:“”

UPDATE:

更新:

JTextField ansTxt;
ansTxt = new JTextField(5);

ansTxt.addKeyListener(new KeyAdapter() {
   public void keyReleased(KeyEvent e) {
    ansTxt = (JTextField) e.getSource();
    String aString = ansTxt.getText().trim();
    int aInt = Integer.parseInt(aString);
   }
}

回答by Thomas L?tzer

You're trying to parse an empty string as an int, which does not work. Which int should "" be parsed as? The JTextField needs to have a text that can be parsed.

您正在尝试将空字符串解析为 int,但这是行不通的。哪个 int 应该被解析为?JTextField 需要有一个可以解析的文本。

ansTxt.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        ansTxt = (JTextField) e.getSource();
        try {
            int aInt = Integer.parseInt(ansTxt.getText());
            //Do whatever you want with the int
        } catch(NumberFormatException nfe) {
            /*
             * handle the case where the textfield 
             * does not contain a number, e.g. show
             * a warning or change the background or 
             * whatever you see fit.
             */
        }
    }
}

It is probably also not a good idea to set ansTxt inside the KeyAdapter. I would suggest you use a local variable for this. That also makes it easier to move the adapter into a "real" class instead of an anonymous one.

在 KeyAdapter 中设置 ansTxt 也可能不是一个好主意。我建议您为此使用局部变量。这也使得将适配器移动到“真实”类而不是匿名类中变得更加容易。

回答by aioobe

The integer argument to the JTextField constructoris actually the widthin number of columns. From the docs:

JTextField 构造函数的整数参数实际上是列数的宽度。从文档:

public JTextField(int columns)

Constructs a new empty TextField with the specified number of columns. A default model is created and the initial string is set to null.

public JTextField(int columns)

构造一个具有指定列数的新空 TextField。创建默认模型并将初始字符串设置为空。

By constructing it with

通过构建它

ansTxt = new JTextField(5);

you'll basically get an empty text-field(slightly widerthan if you constructed it using no-argument constructor). If you want it to contain the string "5" you should write

你基本上会得到一个空的文本字段(比你使用无参数构造函数构造它稍微一些)。如果你想让它包含字符串“5”,你应该写

ansTxt = new JTextField("5");
更新:IIRC,你会得到一个 keyDown 事件,一个 keyTyped 事件,一个 keyUp 事件。大概文本字段尚未在 keyDown 事件上更新。无论哪种方式,我都建议您将 Integer.parseInt 封装在一个
try { ... } catch (NumberFormatException e) { ... }
块,因为用户很可能会写除整数以外的其他内容。-->

回答by Sean

Try introducing the Apache's "commons Lang" library into your project and for your last line you can do

尝试将 Apache 的“ commons Lang”库引入您的项目,对于您的最后一行,您可以这样做

int aInt = 0;
if(StringUtils.isNotBlank(aString) && StringUtils.isNumeric(aString) ){
    aInt = Integer.parseInt(aString);
}

edit: Not sure why the downvote. The JtextField will take any string. If the text field is listening on each key press, every non-numeric value (including blank) that is entered will generate the NumberFormatException. Best to check if it is Numeric before doing anything with the new value.

编辑:不知道为什么downvote。JtextField 将采用任何字符串。如果文本字段在每次按键时都在侦听,则输入的每个非数字值(包括空白)都将生成 NumberFormatException。最好在对新值执行任何操作之前检查它是否为数字。

edit2: As per Thomas' comments below. I ran a test to compare the try/catch vs the StringUtils way of solving this issue. The test was ran 5million times for each. The average time for the try/catch was 21 seconds. The average time for the StringUtils was 8 seconds. So using StringUtils for heavy load is considerably faster. If the load on the code is small you will notice little to no difference. The test ran was

编辑2:根据托马斯在下面的评论。我运行了一个测试来比较 try/catch 与 StringUtils 解决此问题的方法。每个测试运行了 500 万次。try/catch 的平均时间为 21 秒。StringUtils 的平均时间为 8 秒。因此,使用 StringUtils 进行重负载要快得多。如果代码的负载很小,您会发现几乎没有区别。测试运行是

try{
   result = Integer.parseInt(num);
}catch(NumberFormatException ex){
   result = -1;
}

vs

对比

if(StringUtils.isNotBlank(num) && StringUtils.isNumeric(num)){
   result = Integer.parseInt(num);
}else{
   result = -1;
}

each loop through generated a new random string of 10 digits to avoid any optimization in the loops on the if statement. This added 6-7 seconds of overhead.

每次循环都会生成一个新的 10 位数字随机字符串,以避免在 if 语句的循环中进行任何优化。这增加了 6-7 秒的开销。

回答by Ishtar

Your KeyAdapterwill be run before your ansTextwill process the KeyEvent. In fact, you may e.consume()to prevent ansTextfrom processing it at all. So the first time a key is pressed and released, ansText.getText()will still be "". That's why you get the exception first time. Pressing a numerical key twice, should work the second time.

KeyAdapter将在ansText处理 KeyEvent之前运行。事实上,您可以e.consume()完全阻止ansText处理它。因此,第一次按下和释放某个键时,ansText.getText()仍将是""。这就是你第一次得到异常的原因。按两次数字键,应该第二次工作。

回答by Roodra

Use the method trim().

使用方法trim()

int m=Integer.parseInt(txtfield.getText().trim());  

the trim()method will remove any string attached to the number.

trim()方法将删除附加到号码的任何字符串。