0
package code;

public class Solution3 {

    public static int sumOfDigit(String s) {
        int total = 0;
        for(int i = 0; i < s.length(); i++) {
            total = total + Integer.parseInt(s.substring(i,i+1));
        }
        return total;
    }

    public static void main(String[] args) {
         System.out.println(sumOfDigit("11hhkh01"));
    }
}

How can I edit my code to let it ignore any character but still sum up the digit from the input? The error is Exception in thread "main" java.lang.NumberFormatException: For input string: "h"

takendarkk
  • 3,347
  • 8
  • 25
  • 37
users1141df
  • 19
  • 1
  • 6

1 Answers1

0

Because the following line of code will throw a NumberFormatException:

Integer.parseInt("h");

Integer.parseInt does not know how to parse a number from the letter 'h'.

To ignore any characters that are not numbers:

for(int i=0; i<s.length(); i++){
    try {
        total = total + Integer.parseInt(s.substring(i,i+1));
    catch(NumberFormatException nfe) {
        // do nothing with this character because it is not a number
    }
}
Jason
  • 11,744
  • 3
  • 42
  • 46