How to Answer a Programming Question on a Test
Consider the following possible test question.
Write a Java method that receives an int parameter n and
returns n/2 if n is even, and n × 2
if n is odd.
A good solution to this is:
int answer(int n) {
if (n % 2 == 0)
return n / 2;
else
return n * 2;
} // answer()
Things to consider for those who do not want to lose points or for
those who want partial credit:
- The question mentions that the method receives a parameter, so
the solution must include a parameter list.
- The number and types of parameters in the solution must match
those specified in the question. So the parameter list is
one int in this case.
- The values mentioned as returned in the question are probably
integers since n is an int and since 2 is
an int. So the return type should probably
be int. I would also accept a return type of double
since the question is not explicit.
- The question says a value is returned. Thus the answer must
include one or more return statements.
- The question does not mention output. Therefore, any answer
containing a print or println is incorrect.
- The question asks for a method. There is no reason to make up a
class to hold the method.
- Should the method be public, protected, or private? The question
doesn't say, so any choice is okay. The simplest choice is to simply
omit the access specifier.
- Should the method be static? Probably, since it does not use any
data other than the parameter n. But the problem does not say
the method must be static, so either choice is okay.