14

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.

xenteros
  • 15,586
  • 12
  • 56
  • 91
Krunal
  • 77,632
  • 48
  • 245
  • 261

8 Answers8

29

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

NumberUtils.toInt(str, 0);
msfoster
  • 2,474
  • 1
  • 17
  • 19
10

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) {
    try {
       return Integer.parseInt(stringToParse);
    } catch(NumberFormatException ex) {
       return defaultValue; //Use default value if parsing failed
    }
}

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!

Miha_x64
  • 5,973
  • 1
  • 41
  • 63
Yannick
  • 813
  • 8
  • 17
7

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)
mgyongyosi
  • 2,557
  • 2
  • 13
  • 20
6

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;
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
3

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;   
}
Community
  • 1
  • 1
dev_kd
  • 127
  • 1
  • 11
2

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.

xenteros
  • 15,586
  • 12
  • 56
  • 91
  • 1
    Quick Question, usually using try/catch to handle logic flow is an antipattern. I guess in this scenario this is the only option, right? Is verifying that s is not null and is created only using digits, points or that kind of verification better ? – rahpuser Jan 10 '20 at 01:30
0
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;
}
xoX Zeus Xox
  • 195
  • 1
  • 14
-2
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
}
deepakl
  • 172
  • 8
  • 2
    Look, it's one of the answers, but the only one with not even a word to explain... – xenteros Aug 03 '17 at 10:54
  • But that shouldn't be the reason for down vote, anyways I would keep that in mind. – deepakl Aug 03 '17 at 10:58
  • 1
    [Answers with explanations](//meta.stackexchange.com/q/114762) are more useful for future visitors, and more likely to get upvoted. Comment votes don't count for reputation, so they're often used to indicate agreement. If you feel a comment is "too chatty" and ought to be deleted, you can always flag it for moderator attention. – user812786 Aug 03 '17 at 15:32