head firs上的题输出24

img


怎么能输出24啊,试了好久最多20还有点不符合规定,贼烦,求各位帮帮忙,刚刚开始java的学习有好多不懂的。

package test;

public class EchoTestDrive {
    public static void main(String[] args) {
        Echo e1 = new Echo();
        Echo e2 = e1;
        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... 
24

这个题,如果试了好久最多20,说明循环4次每次加1是到不了这个数了。而且还有点不符合规定,应该是部分片段用了2次吧?
换个思路,让程序每次多加点。e1.count加的时候,e2.cout也同时在加。你想到什么了吗?先不往下看,自己想一下


















使用Echo e2 = e1再试试。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^