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
1
Expert's answer
2015-08-07T01:54:21-0400
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)); } }
Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…
APPROVED BY CLIENTS
"assignmentexpert.com" is professional group of people in Math subjects! They did assignments in very high level of mathematical modelling in the best quality. Thanks a lot
Comments
Leave a comment