jeudi 22 juin 2017

Why does the output give 43211234, instead of 43210

This is a problem from the computer science A course description that I don't understand. I expected a value of 43210 because the if statement would reach 0 with (x%10), print it out, and then stop.

When I looked at the Eclipse debugger, I saw the value of x go from 1234, to 123, to 12, to 1... but then it showed the x values going back up to 12, 123, 1234. So the actual output was 43211234.

The question: why does x values work their way back up to the original input?

public class Mystery
{
    public static void main(String []args){
        Mystery strange = new Mystery();
        strange.mystery(1234);
    }

    public void mystery(int x){
        System.out.print(x%10);
        if((x/10) != 0){
            mystery(x/10);
        }
        System.out.print(x%10);
    }
}

Aucun commentaire:

Enregistrer un commentaire