练习吧!1.2.3:奇怪

use*_*571 1 java

我是学习Java的新手,我也在练习它!问题有助于我理解语言.

我陷入问题1.2.3,标题为Strange,在这个问题中,他们希望您根据他们提供的代码输出输出.

我的问题是,与输入相比,我不理解输出.

 public class Strange {

 public static void main(String[] args) {
    first();
    third();
    second();
    third();
 }

 public static void first() {
    System.out.println("Inside first method.");
}

public static void second() {
    System.out.println("Inside second method.");
    first();
 }

 public static void third() {
    System.out.println("Inside third method.");
    first();
    second();
 }
}
Run Code Online (Sandbox Code Playgroud)

我认为输出将是:

Inside first method.
Inside third method.
Inside first method.
Inside second method.
Inside second method.
Inside first method.
Inside third method.
Inside first method.
Inside second method.
Run Code Online (Sandbox Code Playgroud)

但它是:

Inside first method.
Inside third method.
Inside first method.
Inside second method.
Inside first method.
Inside second method.
Inside first method.
Inside third method.
Inside first method.
Inside second method.
Inside first method.
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

非常感谢.

Sea*_*oyd 7

您可以通过应用一些缩进来理解它:

first
third
    first
    second
        first
second
    first
third
    first
    second
        first
Run Code Online (Sandbox Code Playgroud)

(内部节点表示外部节点的方法调用)


Ash*_*mar 5

您应该通过查看每个方法执行的逐步调用来理解这一点.

first();
    Inside first method.
third();
    Inside third method.
        first();
            Inside first method.
        second();
            Inside second method.
                first();
                    Inside first method.
second();
    Inside second method.
        first();
            Inside first method.
third();
    Inside third method.
        first();
            Inside first method.
        second();
            Inside second method.
                first();
                    Inside first method.
Run Code Online (Sandbox Code Playgroud)