I am currently trying to brush up on Java for university using codebat. My goal is to take a string of any ASCII characters, split all of the numbers from the string, then return the sum of all of the numbers as an int.
For example: foo("abc123xyz")
should return 123 and foo("12cd43ad")
should return 55
Here is my code:
public int sumNumbers(String str) {
int sum = 0;
String[] numArr = str.split("\\D+"); //This is my attempted regex
for (String num: numArr) {
sum += Integer.parseInt(num);
}
return sum;
}
When I run sumNumbers("abc123xyz")
or sumNumbers("aa11b33")
, I get this error:
NumberFormatException: For input string: ""
Why is there an empty string in my numArr, and what is the proper regex to solve this issue?