How can I parse String to int with the default value? [duplicate]

≡放荡痞女 提交于 2019-12-07 07:43:08

问题


I need to parse a string user id into integer for that I used Integer.parseInt(String s) but it returns null/nil, if there string has/holds non-decimal/integer value and in that case, I need to assign default integer value as 0.

I tried this but it (? 0) seems not working and I don't know whether it is correct syntax or not.

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

How can assign default value to integer if there is null assignment?

String userid is a parameter argument as part of web service function call, so I cannot update it's data type to integer.


回答1:


You can try this method with a regular expression.

public static int parseWithDefault(String s, int defaultVal) {
    return s.matches("-?\\d+") ? Integer.parseInt(s) : defaultVal;   
}



回答2:


That syntax won't work for Integer.parseInt(), because it will result in a NumberFormatException

You could handle it like this:

String userid = "user001";
int int_userid;
try
{
   int_userid = Integer.parseInt(userid);
}
catch(NumberFormatException ex)
{
   int_userid = 0;
}

Please note that your variable names do not conform with the Java Code Convention


A better solution would be to create an own method for this, because I'm sure that you will need it more than once:

public static int parseToInt(String stringToParse, int defaultValue)
{
    int ret;
    try
    {
       ret = Integer.parseInt(stringToParse);
    }
    catch(NumberFormatException ex)
    {
       ret = defaultValue; //Use default value if parsing failed
    }
    return ret;
}

Then you simply use this method like for e.g.:

int myParsedInt = parseToInt("user001", 0);

This call returns the default value 0, because "user001" can't be parsed.

If you remove "user" from the string and call the method...

int myParsedInt = parseToInt("001", 0);

…then the parse will be successful and return 1 since an int can't have leading zeros!




回答3:


You're most likely using apache.commons.lang3 already:

NumberUtils.toInt(str, 0);



回答4:


You can use this way with String::matches like this :

String userid = "user001";
int int_userid = userid.matches("\\d+") ? Integer.parseInt(userid) : 0;

You ca also use -?\d+ for both positive and negative values :

int int_userid = userid.matches("-?\\d+") ? Integer.parseInt(userid) : 0;



回答5:


It might be a little over-engineering, but you can use Guava's Ints.tryParse(String) with Java 8's Optionals like this:

int userId = Optional.ofNullable(Ints.tryParse("userid001")).orElse(0)



回答6:


I believe that you can achieve what you want by the following method:

public static int parseIntWithDefault(String s, int default) {
    try {
        return Integer.parseInt(s);
    } catch(NumberFormatException e) {
        return default;
    }
}

and now just assign:

int int_userid = parseIntWithDefault(userId, 0);

Please have in mind, that using Java one should use Java good practices about formatting the code. int_userid is definitely something to improve.




回答7:


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

Did you mean this syntax? But since an int can never be null you have to instead do:

String userid = "user001";
int int_userid;
try { 
    int_userid= Integer.parseInt(userid);
} catch (NumberFormatexception e) {
    int_userid = 0;
}



回答8:


int int_userid;
try {
    int_userid = Integer.parseInt(userid); // try to parse the given user id
} catch (Exception e) {   // catch if any exception
    int_userid = 0; // if exception assign a default value
}


来源:https://stackoverflow.com/questions/45481560/how-can-i-parse-string-to-int-with-the-default-value

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