Proper way to avoid parseInt throwing a NumberFormatException for input string: “”

后端 未结 7 834
小鲜肉
小鲜肉 2020-12-06 09:53

When I run parseInt:

Integer.parseInt(myString);

it throws:

NumberFormatException: For input string: \"\"

相关标签:
7条回答
  • 2020-12-06 10:37

    Integer.parseInt(String) doesn't accept non-numeric input, including nulls and empty strings.

    Either guard against that like you suggested, or catch the NFE.

    0 讨论(0)
  • 2020-12-06 10:38

    Yes, but: Wrap it in a thin method (and eliminate the redundant else), or use an existing implementation, like Commons Lang's NumberUtils.toInt(str, defaultValue):

    NumberUtils.toInt(myString, 0);
    

    This method handles null values and conversion failures.

    Writing the same thing on your own is straight-forward:

    • Check for null, and/or...
    • ...Wrap the NumberFormatExtension exception
    0 讨论(0)
  • 2020-12-06 10:38

    If the string can be empty I do it this way:

    Integer.parseInt("0" + inputString)
    

    When I'm not sure it contains only digits:

    Integer.parseInt(0 + inputString.replaceAll("\\D+",""))
    
    0 讨论(0)
  • 2020-12-06 10:39

    What you have is fine, but as a coding style I prefer to make tests "positive" (isBlank), rather than "negative" (isNotBlank), ie

    if (StringUtils.isBlank(myString)) {
        return 0;
    }
    return Integer.parseInt(myString); // Note: No need for else when the if returns
    

    or, more succinctly:

    return StringUtils.isBlank(myString) ? 0 : Integer.parseInt(myString);
    
    0 讨论(0)
  • 2020-12-06 10:51

    Yes. (Validate your inputs before making assumptions about what are in them. :-)

    +1 for already finding Apache's common-lang w/ StringUtils.

    0 讨论(0)
  • 2020-12-06 10:53

    Well, you could use the conditional operator instead:

    return StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
    

    If you need to do this in multiple places, you'd probably want to put this into a separate method. Note that you should also consider situations where myString is null, or contains non-numeric text.

    0 讨论(0)
提交回复
热议问题