java.lang.NumberFormatException: For input string: “”

烈酒焚心 提交于 2019-11-28 05:29:44

问题


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: ""

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

回答1:


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

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.

By constructing it with

ansTxt = new JTextField(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");
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) { ... }
block since the user may very well write something else than an integer. -->


回答2:


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.

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.




回答3:


Use the method trim().

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

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




回答4:


Your KeyAdapter will be run before your ansText will process the KeyEvent. In fact, you may e.consume() to prevent ansText from 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.




回答5:


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

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.

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

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.



来源:https://stackoverflow.com/questions/3701520/java-lang-numberformatexception-for-input-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!