Hello everyone. I’m filling out this questionnaire and I’m being asked these questions about the below snippet of code. I’m a pretty seasoned web developer, but I’m not sure what language this is in. It looks like maybe Java or C++, but I’m not too sure.
So this is what I need to answer:
[FONT=Verdana]a) Explain what the code is supposed to do.[/FONT]
[FONT=Verdana]b) Identify any errors in the code.[/FONT]
[FONT=Verdana]c) If there are errors, please fix them.
[/FONT] Here is the code:
[FONT=Verdana]public String mystery(String num) {[/FONT]
[FONT=Verdana] if (num == null) {[/FONT]
[FONT=Verdana] return "N/A";[/FONT]
[FONT=Verdana] }[/FONT]
[FONT=Verdana] int len = num.length();[/FONT]
[FONT=Verdana] int c = 0;[/FONT]
[FONT=Verdana] char[] sb = new char[len];[/FONT]
[FONT=Verdana] for (int i = 0; i < len; i++) {[/FONT]
[FONT=Verdana] sb[c++] = num.charAt(i);[/FONT]
[FONT=Verdana] if ((len - 1 - i) % 3 == 0 && i != len - 1) {[/FONT]
[FONT=Verdana] sb[c++] = ',';[/FONT]
[FONT=Verdana] }[/FONT]
[FONT=Verdana] }[/FONT]
[FONT=Verdana] return new String(sb);[/FONT]
[FONT=Verdana] }[/FONT]
I can identify some errors, but I’m not really sure what it is supposed to do. Thanks!
a) it’s a member function that is supposed to take a string and return a new string with the same content as the old string but with a comma inserted between every 3 letters.
b) it does not correctly allocate enough storage for the new string.
c) char[] sb = new char[len + (len / 3)];
[QUOTE=kirupa;2350048]Are you asking us to do your homework for you? [/QUOTE]
He said filling out a questionnaire… More likely his college application.
It’s not C++, it’s Java. In C++ the string type is called std::string, not String, and NULL is used to check pointer values, not whole strings. Also, String.charAt is a typical Java method. Also, in C++ public methods are grouped under a public header, they do not each have a public modifier.
[QUOTE=Voetsjoeba;2350091]It’s not C++, it’s Java. In C++ the string type is called std::string, not String, and NULL is used to check pointer values, not whole strings. Also, String.charAt is a typical Java method. Also, in C++ public methods are grouped under a public header, they do not each have a public modifier.
Also, do your own homework.[/QUOTE]
But but but, he could have used the std namespace… and then made a custom class of string that mimics String, and overloaded the == operator to compare with booleans/integers… Then would it be C++?