I am going through the CodingBat exercises for Java. Here is the task I have just completed:
Given a
string
, return the sum of the numbers appearing in thestring
, ignoring all other characters. A number is a series of 1 or more digit chars in a row.
And here is my code:
public int sumNumbers(String str){
int total = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
StringBuilder appendNums = new StringBuilder();
appendNums.append(str.charAt(i));
for (int j = i+1; j < str.length(); j++) {
if (Character.isDigit(str.charAt(j))) {
appendNums.append(str.charAt(j));
} else {
break;
}
}
String appendNums2String = appendNums.toString();
total += Integer.parseInt(appendNums2String);
i += appendNums2String.length()-1;
}
}
return total;
}
The questions I have are:
- Are there any parts of this code you find to be poor practise or poor quality?
- Is it acceptable to append one digit before the (conditional) digits that proceed it, or should I be identifying the entire block first, and then append?
- What is a more concise way of solving this?
- For this question I relied heavily on Eclipse's debugger until I got it right. Is this good or bad practise?
- Is it a better idea to use a
while
loop instead of the secondfor
loop, because the characters tested are relative toi
rather than thestring
's length? (I played around with this but couldn't figure it out.)