0

My goal is to take the digits out of a string and convert it to an int. For example: 12.7 (string) would become 127 (int) 156-06 (string) would become 15606 (int)

This is the code I used:

private static int convertToDigits(String input){
    StringBuilder sb = new StringBuilder(input.length());
    for(int i = 0; i < input.length(); i++){
        char c = input.charAt(i);
        if(c > 47 && c < 58){
            sb.append(c);
        }
    }
    String result = sb.toString().trim();
    Log.d("Result", result);
    return Integer.parseInt(result);
}

When I log the result I am getting 127 as the string value I want, but when I convert that to an int, I get a NumberFormatException:

java.lang.NumberFormatException: Invalid int: ""
        at java.lang.Integer.invalidInt(Integer.java:138)
        at java.lang.Integer.parseInt(Integer.java:358)
        at java.lang.Integer.parseInt(Integer.java:334)
        at com.dcasillasappdev.mytrackfieldteam.utility.Utility.convertToDigits(Utility.java:333)

Am I missing something here? Thanks in advance!

janos
  • 120,954
  • 29
  • 226
  • 236
TrackDave
  • 279
  • 2
  • 14

1 Answers1

2

Am I missing something here?

Yes, the case of empty input. Your method works fine for non-empty strings, you just need to add special treatment for empty input, for example:

if (input.isEmpty()) {
    return 0;  // or whatever way you want to handle this case ...
}

Btw, here's a simpler way to strip all non-digit characters and convert to an int:

return Integer.parseInt(input.replaceAll("\\D+", ""));

But if you really want to stick to your original approach iterating over the characters and using a string builder, then here's a better way to write that:

private static int convertToDigits(String input) {
    if (input.isEmpty()) {
        return 0;
    }
    StringBuilder builder = new StringBuilder(input.length());
    for (char c : input.toCharArray()) {
        if('0' <= c && c <= '9') {
            builder.append(c);
        }
    }
    return Integer.parseInt(builder.toString());
}
janos
  • 120,954
  • 29
  • 226
  • 236
  • I also tried running your method and I'm still getting "Invalid int: "". I'm confused why I'm getting an empty input when my log is showing a valid int. – TrackDave Oct 02 '15 at 18:16
  • i figured out what went wrong. Janos your answer was helpful. – TrackDave Oct 02 '15 at 19:06