Вопрос

I am currently learning the basics of Java from a book and I've got this code as an example of Nested Loops using Recursion. I understand everything, but the usage of return function in the end of the code. I cannot figure out how the program decide, when to stop exactly when K=4. I've tried to debug it and this continued to be like a mystery for me. Here is the code :

import java.util.Scanner;

public class nestedLoops {
public static int numberOfLoops;
public static int numberOfIterations;
public static int[] loops;

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("N = ");
    numberOfLoops = input.nextInt();

    System.out.print("K = ");
    numberOfIterations = input.nextInt();

    input.close();

    loops = new int[numberOfLoops];

    nestedLoops(0);
}

public static void nestedLoops(int currentLoop) {
    if (currentLoop == numberOfLoops) {
        printLoops();
        return;
    }

    for (int counter=1;counter<=numberOfIterations;counter++) {
        loops[currentLoop] = counter;
        nestedLoops(currentLoop + 1);
    }
}

public static void printLoops() {
    for (int i = 0; i < numberOfLoops; i++) {
        System.out.printf("%d ", loops[i]);
    }
    System.out.println();
}
}

It would be very helpful if someone explain me how return works in this particular example in the end when numbers are "4.4" and also how it works at all in a void method, because I've been searching for explanation of that but did not succeed...

Thank you beforehand !

Это было полезно?

Решение

A return statement in a void method stops running the method and returns back to the calling code. In this example with the input:

numberOfLoops = 4
numberOfIterations = 4

Right after taking the input, you create an array based off of the input and then call the nestedLoops(0) method:

public static void nestedLoops(int currentLoop) {
    if (currentLoop == numberOfLoops) {
        printLoops();
        return;
    }

    for (int counter=1;counter<=numberOfIterations;counter++) {
        loops[currentLoop] = counter;
        nestedLoops(currentLoop + 1);
    }
}

The explanation

For starts, let's just ignore the for loop. The if statement checks to see if currentLoop == numberOfLoops and it does this every time this method is called. Right now currentLoop is 0 (the value we passed into this method when we called it) and numberOfLoops is 4 (the value we entered at the very beginning) so this is false and none of the code inside is called.

The for loop below the if statement is going to run numberOfIterations times. In our case, this loop is going to run 4 times. I will write out what happens below in sequential order:

 - input is 4, 4
 - nestedLoops(0) called- currentLoop = 0
 - if evaluates to false
 - for loop runs
     - loops[0] = 1
     - nestedLoops(1)
     - if evaluates to false ( 1 != 4)
     - for loop runs
          - loops[1] = 1
          - nestedLoops(2)
          - if evaluates to false (2 != 4)
          - for loop runs
              - loops[2] = 1
              - nestedLoops(3)
              - if evaluates to false (3 != 4)
              - for loop runs
                  - loops[3] = 1
                  - nestedLoops(4)
                  - if evaluates to TRUE (4 == 4)
                  - loops are printed (all values are 1 right now)
                  -returns to calling location
              -Which is the for loop associated with this indention. 
              -For loop increments, and then sets loops[3] = 2.
           - then this loop finishes
       - then this loop finishes
 etc. etc.

The return in a void method just means "okay, stop what you're doing and go back to who/whatever called this and move on" In this case its jumping back to previous for loop to keep working.

Другие советы

The for loop inside the nestedLoops method is calling itself numberOfIterations times. So it goes 0, then makes numberOfIterations calls. So if you entered 4 you would see 4 calls with currentLoop=1 then 16 calls with currentLoop=2 and so on....

When all else fails write some code to debug your code. I am a visual person myself so making some output helps when the debugger doing it for me.

public static HashMap<Integer, Integer> map = new HashMap();

public static void main(String[] args) {
    ....
    System.out.println(map);
}

public static void nestedLoops(int currentLoop) {
    if(map.containsKey(currentLoop)) {
        map.put(currentLoop, map.get(currentLoop)+1);
    } else {
        map.put(currentLoop, 1);
    }
    ...
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top