Answer to Question #53966 in Java | JSP | JSF for NB

Question #53966
Im learning Java through the codingbat website. Im working on problem http://codingbat.com/prob/p121193 I have coded: if (str.length() == 0) return 0; int sum=0; int start = 0; int stop=0; int f=0; int j=0; for (int i=0;i<str.length()-1;i++){ if (Character.isDigit(str.charAt(i))){ start = i; if (i == str.length()-1) stop = i; for (j=i+1 ;j < str.length()-1;j++){ if (!Character.isDigit(str.charAt(j))){ i = j; stop = j; j = j+ str.length();} else {stop = j;} } sum += Integer.parseInt(str.substring(start,stop)); } } return sum; } This code passes a few of the tests. When value "aa11b33" enters the program and "start" (i) = 5, the "for" loop should start at j=6. In trying to figure out whats wrong, I commented out the "sum+=...." code and returned "stop". It returns a result of 4. Looking for advice on why this is happening. Thanks in advance NB
Expert's answer
if (str.length() == 0)
return 0;
str = str + " ";
int sum = 0;
int start = 0;
int stop = 0;
int f = 0;
int j = 0;

for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
start = i;
if (i == str.length() - 1) {
stop = i;
} else {
for (j = i + 1; j < str.length(); j++) {
if (!Character.isDigit(str.charAt(j))) {
i = j;
stop = j;
j = j + str.length();
} else {
stop = j;
}
}
}
sum += Integer.parseInt(str.substring(start, stop));
}
}

return sum;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS
paypal