java.lang.NumberFormatException:对于输入字符串: [英] java.lang.NumberFormatException: For input string: ""

查看:774
本文介绍了java.lang.NumberFormatException:对于输入字符串:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码时:

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

为什么会出现此错误?

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

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

更新:

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

推荐答案

The integer argument to the JTextField constructor is actually the width in number of columns. From the docs:

public JTextField(int columns)

使用指定的列数构造一个新的空TextField.将创建一个默认模型,并将初始字符串设置为null.

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

通过构建它

ansTxt = new JTextField(5);

您基本上会得到一个空文本字段(比使用无参数构造函数构造的文本字段宽()).如果要包含字符串"5",请输入

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

ansTxt = new JTextField("5");

更新: IIRC,您将为keyDown获得一个事件,为keyTyped获得一个事件,并为keyUp获得一个事件.推测文本字段尚未在keyDown事件上更新. 无论哪种方式,我建议您将Integer.parseInt封装在

Update: IIRC, you'll get one event for keyDown, one for keyTyped, and one for keyUp. Presumably the text-field has not yet been updated on the keyDown event. Either way I suggest that you encapsulate the Integer.parseInt in a

try { ... } catch (NumberFormatException e) { ... }

这篇关于java.lang.NumberFormatException:对于输入字符串:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆