I am trying to produce the sum of numbers in a string.
public int sumNumbers(String str) {
int sum = 0;
for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length() - 1; j++) {
if (!Character.isDigit(str.charAt(j))) {
i = j;
break;
} else if (Character.isDigit(str.charAt(j + 1))) {
continue;
}
sum += Integer.parseInt(str.substring(i, j + 1));
}
}
return sum;
}
For example, if I have sumNumbers("aa11b33")
it should return 44
. However, it's returning 11
.
I'm assuming this is because the outer loop is terminating due to the break
or continue
statements. Is that the problem? If so, what should I do?