Simulating nested loops

后端 未结 2 828
耶瑟儿~
耶瑟儿~ 2020-12-18 17:21

In a beginner\'s programming book (free licence) there was the following code, dynamically creating nested loops in Java:

import java.util.Scanner;

public c         


        
相关标签:
2条回答
  • 2020-12-18 17:41

    Because it's a recursive call to nested loops. first, it is called with 0. then it is called with 1. then with 2. when it gets to the number of total loops, it begins executing the loops (this is called the recursive terminal condition). however, each call to nested loops is placed on the stack, it executes k, then returns and executes k-1, then returns and executes k-2, then returns and executes k-3 all the way down to k - k = 0.

    if i were you, i would place a breakpoint on the call of nestedloops() inside itself and watch what it is being called with. then, as it is called, watch it work its way back down.

    0 讨论(0)
  • 2020-12-18 17:44

    It might be solved with this library, for example.

    In your case you can implement loops so:

    new Loops()
        .from(1).to(4)
        .from(1).to(4)
        .action(System.out::println);
    

    The result:

    [1, 1]
    [1, 2]
    [1, 3]
    [2, 1]
    [2, 2]
    [2, 3]
    [3, 1]
    [3, 2]
    [3, 3]
    
    0 讨论(0)
提交回复
热议问题