如何计算此程序中的最终输出打印数量?

时间:2013-10-05 03:07:21

标签: java

这是教科书中的练习课程。我需要弄清楚这个程序的输出。 这是该计划:

public class EchoTestDrive {
    public static void main(String[] args) {
        Echo e1 = new Echo();
        Echo e2 = new Echo();

        int x = 0;
        while (x < 4) {
            e1.hello();
            e1.count = e1.count + 1;
            if (x == 3) {
                e2.count = e2.count + 1;
            }
            if (x > 0) {
                e2.count = e2.count + e1.count;
            }
            x = x + 1;
        }
        System.out.println(e2.count);
    }
}

class Echo {
    int count = 0;

    void hello() {
        System.out.println("helloooo... ");
    }
}

该计划的外页答案是:

helloooo...
helloooo...
helloooo...
helloooo...
10

我不太明白这是怎么计算的。似乎x循环了4次。 X = 0; X = 1; X = 2; X = 3。并且e1应该具有值1,2,3,4,因为e1.count = e1.count + 1。 然后我很困惑,在这种情况下如何计算e2?

2 个答案:

答案 0 :(得分:1)

观察变量输出

public class EchoTestDrive {
    public static void main(String[] args) {
        Echo e1 = new Echo();
        Echo e2 = new Echo();

        int x = 0;
        while (x < 4) {
            e1.hello();
            e1.count = e1.count + 1;
            System.out.println("e1.count = " + e1.count);
            if (x == 3) {
                e2.count = e2.count + 1;
                System.out.println("x == 3 e2.count = " + e2.count);
            }
            if (x > 0) {
                e2.count = e2.count + e1.count;
                System.out.println("x > 0 e2.count = " + e2.count);
            }

            x = x + 1;
        }
        System.out.println(e2.count);
    }
}

答案 1 :(得分:0)

组成一个x,e1.count和e2.count的表。然后只需按照程序并逐行更新值。我得到e2.count的最终值10。对于x = 0,e2.count保持为0。但它在x = 3时得到额外的增量。