Выход рекурсии не такой, как ожидалось - PullRequest
0 голосов
/ 07 апреля 2019

Кто-нибудь может выяснить, как работает этот код рекурсии и почему он выводит то, что он делает?
Может быть, вы могли бы включить шаги, которые он проходит, чтобы получить то, что он выводит? Спасибо вам большое! Код прикреплен ... (выводится bdefh).
Также обратите внимание, что я новичок.

public class difficult {

    public static void main(String[] args) {
        mysteryMix("abcdefgh!");
    }

    public static void mysteryMix(String str) {
        System.out.println("i entered loop");
        System.out.println(str);
        int length=str.length();
        if(length>=3)
        {
            System.out.println(str);
            System.out.println("I entered if statement");
            mysteryMix(str.substring(0,length/3));
            System.out.println(str);
            System.out.println("FOR REAL PRINT: " +str.substring(length/3,2*length/3));
            System.out.println("length "+length);
            System.out.println(length/3);
            System.out.println(2*length/3);
            mysteryMix(str.substring(2*length/3));
        }   
    }
}

1 Ответ

0 голосов
/ 07 апреля 2019
Relevant statement                                      Output
=================================================       ======================
mysteryMix("abcdefgh!")
  System.out.println("i entered loop");                 i entered loop
  System.out.println(str);                              abcdefgh!
  System.out.println(str);                              abcdefgh!
  System.out.println("I entered if statement");         I entered if statement
  mysteryMix("abc")
    System.out.println("i entered loop");               i entered loop
    System.out.println(str);                            abc
    System.out.println(str);                            abc
    System.out.println("I entered if statement");       I entered if statement
    mysteryMix("a")
      System.out.println("i entered loop");             i entered loop
      System.out.println(str);                          a
    System.out.println(str);                            abc
    System.out.println(...);                            FOR REAL PRINT: b
    System.out.println("length "+length);               length 3
    System.out.println(length/3);                       1
    System.out.println(2*length/3);                     2
    mysteryMix("c")
      System.out.println("i entered loop");             i entered loop
      System.out.println(str);                          c
  System.out.println(str);                              abcdefgh!
  System.out.println(...);                              FOR REAL PRINT: def
  System.out.println("length "+length);                 length 9
  System.out.println(length/3);                         3
  System.out.println(2*length/3);                       6
  mysteryMix("gh!")
    . . . and so forth
...