1

私は Java を学ぶのが初めてで、Practice-It! を行っています。言語を理解するのに役立つ質問。

Strange というタイトルの問題 1.2.3 に行き詰まっています。この質問では、提供されたコードに基づいて出力を入力してほしいとのことです。

私の質問は、入力と比較して出力を理解していないということです。

 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();
 }
}

出力は次のようになると思いました:

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.

しかし、それは次のとおりです。

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.

どうしてこれなの?

どうもありがとう。

4

6 に答える 6

7

インデントを適用することで理解できます。

first
third
    first
    second
        first
second
    first
third
    first
    second
        first

(内側のノードは、外側のノードによるメソッド呼び出しを表します)

于 2013-09-30T10:02:45.667 に答える
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.
于 2013-09-30T10:07:41.530 に答える
3

デバッガーを起動し、そのコードをステップ実行する必要があります。そうすれば、いつ何が行われるかがわかります。

ここで物事を説明する際の問題は、それがすべきことを行うということです (したがって、プログラムの出力は私が期待するものです)。

(うまくいけば)使用しているIDEでデバッガーを見つけることができます。ここにブレークポイントを追加するfirst();必要があり、必要なすべてのメソッドに「ステップイン」するか、System.out.println.

于 2013-09-30T10:02:12.830 に答える
2
public static void first() {
    System.out.println("Inside first method.");
}

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

を呼び出すたびにsecond()、次の行が連続して表示されます (first()が直後に呼び出されるため)。

Inside second method.
Inside first method.

これは、" Inside second method." を印刷できる唯一の方法でもあります。したがって、期待するこの出力は不可能です。

...
Inside second method.
Inside second method.
于 2013-09-30T10:08:51.703 に答える
1

あなたの secondMethod() には firstMethod() への呼び出しがあるため、すべての「Inside Second Method」の直後に「Inside First Method」が表示されます。secondMethod() 内の firstMethod() の呼び出しを削除すると、期待される出力が表示されます

于 2013-09-30T10:02:36.040 に答える