6

I want to check is a String I pass to Integer.valueOf(String s) a valid String to parse. If one is not parsable I need to return 0.

I do it in the following way:

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

Is it a bad way to do that?

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 1
    No. It isn't bad (because you are handling the exception). Although you could also do `string.matches("\\d+")` to see if it contains only digits. – TheLostMind Sep 29 '14 at 11:16
  • I don't consider it _bad_, but there are better ways to do it. A simple `while` that checks if every character is a digit (beware that the first can also be `+` or `-`), or a regex-matching would be better IMO. This would avoid generating the stack trace if the string is not parseable – BackSlash Sep 29 '14 at 11:16
  • Decimal are also nubbers but the regex should be fine for Integer. – Mite Mitreski Sep 29 '14 at 11:17
  • There are negative integers as well. – Marko Topolnik Sep 29 '14 at 11:18
  • possible duplicate of [Java: Good way to encapsulate Integer.parseInt()](http://stackoverflow.com/questions/1486077/java-good-way-to-encapsulate-integer-parseint) – O. Jones Sep 29 '14 at 11:18
  • possible duplicate of [Does java have a int.tryparse that doesn't throw an exception for bad data?](http://stackoverflow.com/questions/8391979/does-java-have-a-int-tryparse-that-doesnt-throw-an-exception-for-bad-data) – Alex K. Sep 29 '14 at 11:19
  • @MarkoTopolnik And what is? Can it be a trouble in that way? – St.Antario Sep 29 '14 at 11:19
  • Just commenting on the `\\d+` regex... – Marko Topolnik Sep 29 '14 at 11:21
  • 1
    I think your code is as good as it gets. Also note that HotSpot has specific optimizations for exceptions which are caught on the spot and not dereferenced in the catch-block. It will compile to exactly the code you'd want it to (no stack trace generated, etc.). – Marko Topolnik Sep 29 '14 at 11:25
  • I agree with Marko. Another case that the regex doesn't handle is decimals (e.g. "20.0"). You could code a regex to handle this, but what do you gain? – Mansoor Siddiqui Sep 29 '14 at 11:29
  • 1
    @MansoorSiddiqui No need to handle decimals for an integer. – Marko Topolnik Sep 29 '14 at 11:36
  • 1
    I meant integers with a ".0" at the end. Integer.parseInt(String) will parse those just fine. – Mansoor Siddiqui Sep 29 '14 at 12:13

3 Answers3

6

method 1: use a regular expression to check for validity of being a number

public static int parseStrToInt(String str) {
        if (str.matches("\\d+")) {
            return Integer.parseInt(str);
        } else {
            return 0;
        }
    }

method 2: use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric

public static int strToInt(String str) {
    NumberFormat formatter = NumberFormat.getInstance();
    ParsePosition pos = new ParsePosition(0);
    formatter.parse(str, pos);

    if (str.length() == pos.getIndex()) {
        return Integer.parseInt(str);
    } else {
        return 0;
    }
}
Vipul Paralikar
  • 1,508
  • 10
  • 22
  • 4
    I think the string should match `[+-]?\d+`. There can be negative integers (so the strings starts with `-`) and positive integers which are written starting with `+` – BackSlash Sep 29 '14 at 11:30
4

I would have used:

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
yaser eftekhari
  • 235
  • 1
  • 6
1

Hi this will do even the number is double or long, which is useful always while parsing.

List<String> myStrings = new ArrayList<String>();

myStrings.add("text");
myStrings.add("25");
myStrings.add("102.23333333");
myStrings.add("22.34");

NumberFormat nf = NumberFormat.getInstance();
for( String text : myStrings){
    try {
        System.out.println( nf.parse(text));
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56