0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 3
    1. `continue` and `break` only affect the directly enclosing loop 2. Step through your code using a debugger to see why it isn't working properly – UnholySheep Oct 28 '17 at 14:03
  • 3
    *"I'm assuming this is because the outer loop is terminating due to the `break` or `continue` statements."* Nope. Rather than guessing, use the debugger built into your IDE to step through the code statement-by-statement and watch exactly what it does. – T.J. Crowder Oct 28 '17 at 14:03

0 Answers0