mercredi 8 mars 2017

Puzzled about the way JAVA handles this workflow and reference situation. Can someone clarify?

I am quite uncertain about the way java flows through this simple code. I have managed to make it work, but I don't really understand why the problems that occur (see in code comments) unfold as they do.

More specifically:

  • Why is there such a difference in functionality between "newCounter" and "counter++"?

  • Why does counter++ work well for recursion while newCounter doesn't?

  • Why does java catch only the first counter++ "else if" condition statement, but not the second one?

  • And why does java catch both "else if" statements when I use newCounter instead of counter++ I feel as though there might be some important principles into the way java is working that I am missing and should learn.

Any clarification about this or reference to key concepts/issues that are in play here would be very much appreciated.

Thanks, CodeAt30

System.Out.println(*grow*(1));

static int *grow*(int counter) {

    int newCounter = counter++;
    int limit = 8;

    if (newCounter < limit) {

        System.out.println("Counter: " + counter);
        System.out.println("New Counter: " + newCounter);   
        return counter * grow(counter++);                   // If I use newCounter here I loop out to failure as the number stays static (always under limit)
                                                            // counter++ does work though, providing a good <number>! calculation (7! or 6! etc.).      
    } else if (newCounter % 2 == 0) {                       
                                                            // If I use counter++ instead of newCounter in both "else if" statements though,
        System.out.println("even number");                  // java only catches the first one. An odd number is not caught,
        return 1;                                           // and final "else" statement is invoked. newCounter works well though.

    } else if (newCounter % 2 == 1) {

        System.out.println("odd number");
        return -1;

    } else {                                                // I do not want to reach this final else possibility.

        System.out.println("Got to else.....");
        return 0;

    }
}

Aucun commentaire:

Enregistrer un commentaire