The following is my adaptation of an AP Computer Science question. The book says it should print 00100123 I think it should print 0010012 But the code below actually prints 3132123
What is going on? Also it does not appear to have any stop condition?!
public class Mystery {
public static void main(String[] args) {
int n;
n = 3;
mystery(n);
}
public static void mystery(int n) {
int k;
for (k = 0; k < n; k++) {
mystery(k);
System.out.print(n);
}
}
}
The actual question reads: Consider the following method.
public void mystery (int n)
{
int k;
for (k=0 ; k < n ; k++)
{
mystery(k);
System.out.print(n);
}
}
What value is returned by the call mystery (3)?
I now understand that the loop forms the stop condition and I think I understand jhamon's comment "last instruction is to print n. n is 3, there is no way it prints only '0010012'" but I don't understand why the book says it should print 00100123.
As Batsheba says I have tried watching the variables while debugging but the book says it should print 00100123. Thanks very much jhamon for the corrected code, so from what I can see the book is wrong?
n.nis 3, there is no way it prints only '0010012'Also it does not appear to have any stop condition?!It has one:k<nin theforloop. Can you also post the question you are trying to solve?k<nbecomes the stop condition. In fact, the whole thing is obvious if you use a line by line debugger, or run the code logically in your head.printis not at the right place, try to move it out of the loop