I am supposed to say what this function does and identify any errors.
public String mystery(String num) {
if (num == null) {
return "N/A";
}
int len = num.length();
int c = 0;
char[] sb = new char[len];
for (int i = 0; i < len; i++) {
sb[c++] = num.charAt(i);
if ((len - 1 - i) % 3 == 0 && i != len - 1) {
sb[c++] = ',';
}
}
return new String(sb);
}
I see there is an ArrayIndexOutOfBoundsException, but I'm stuck there. First it grabs len which is the length of the string "test" would be 4. I'm thinking this is supposed to take the string passed in and separate the characters with commas, so "test" would return "t,e,s,t". And I think the problem is with the incrementing of c.
Any help would be greatly appreciated.
TIA,
JS
public String mystery(String num) {
if (num == null) {
return "N/A";
}
int len = num.length();
int c = 0;
char[] sb = new char[len];
for (int i = 0; i < len; i++) {
sb[c++] = num.charAt(i);
if ((len - 1 - i) % 3 == 0 && i != len - 1) {
sb[c++] = ',';
}
}
return new String(sb);
}
I see there is an ArrayIndexOutOfBoundsException, but I'm stuck there. First it grabs len which is the length of the string "test" would be 4. I'm thinking this is supposed to take the string passed in and separate the characters with commas, so "test" would return "t,e,s,t". And I think the problem is with the incrementing of c.
Any help would be greatly appreciated.
TIA,
JS