Java – to check whether a string can be parsed to an integer?

I want to check a string I pass to integer Valueof (string s) a valid string to parse If one is not parsed, I need to return 0

I did it in the following ways:

try{
    Integer.valueOf(String s)
} catch(NumberFormatException e) {
    return 0;
}

Is this a bad way?

Solution

I will use:

s = s.trim(); // sometimes user inputs white spaces without kNowing it
int value;
if (s.length() == 0) {
    value = 0; // obvIoUsly not a string
} else {
    try{
        value = Integer.valueOf(s);
    } catch(NumberFormatException e) {
        value = 0;
    }
}

// do whatever you like here
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>