Java – how do I resolve a string to int using default values?

See English answers > good way to encapsulate integer Parseint() 22

I've tried this, but it (? 0) doesn't seem to work. I don't know if it's the correct grammar

String userid = "user001";
int int_userid = Integer.parseInt(userid) ? 0;

If there is an empty assignment, how do I assign the default value to an integer?

The string userid is a parameter as part of a web service function call, so I cannot update its data type to an integer

Solution

You can try this method using regular expressions

public static int parseWithDefault(String s,int default) {
    return s.matches("-?\\d+") ? Integer.parseInt(s) : default;   
}
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
分享
二维码
< <上一篇
下一篇>>