这个程序的输出应该是什么?

时间:2012-12-12 05:20:24

标签: java

如果你打电话给第一种方法'CreateLotsOfAlphas',它应该打印什么?我在跟踪程序流程时遇到了麻烦。我认为它会打印aabbc,但由于某种原因它实际上打印了bacbc。

我的理由是newA1.y只是输入,a,起初是由于null。 a被保存到this.y中,所以newA2.y是(a + b),b保存到this.y中,然后newA3.y是(b + c)给aabbc。

我是在看这个错误还是什么?

public void CreateLotsOfAlphas() {
    Alpha newA1 = new Alpha(1.0, "a", null); 
    Alpha newA2 = new Alpha(2.0, "b", newA1); 
    Alpha newA3 = new Alpha(3.0, "c", newA2);
    System.out.println(newA1.y + newA2.y + newA3.y);
}

顺便提一下,这两种方法分为两类。

public Alpha(double x, String y, Alpha oldAlpha) { 
    this.x = x;
    this.y = y;
    w = (int) x;
    if (oldAlpha != null) { 
        oldAlpha.y = y + oldAlpha.y;
    } 
}

4 个答案:

答案 0 :(得分:1)

在印刷声明时

newA3.y = 'c'
newA2.y = 'cb'
newA1.y = 'ba'

答案 1 :(得分:1)

Alpha newA1 = new Alpha(1.0, "a", null);
// oldAlpha == null so we only newA1.y = "a"
Alpha newA2 = new Alpha(2.0, "b", newA1);
// oldAlpha is newA1 => newA1.y = "b"+"a"; newA2.y = "b"
Alpha newA3 = new Alpha(3.0, "c", newA2);
// oldAlpha is newA2 => newA2.y = "c"+"b", newA3.y = "c"; newA1.y = "ba" (still)
System.out.println(newA1.y + newA2.y + newA3.y);
// newA1.y = "ba", newA2.y = "cb", newA3.y = "c"

......足够清楚了吗?

答案 2 :(得分:0)

这是因为你在第一次调用构造函数时遇到null它无法进入if if条件或者条件没有执行

if (oldAlpha != null) { 
        oldAlpha.y = y + oldAlpha.y;
    } 

答案 3 :(得分:0)

只有当旧Alpha不为null时,才会实际打印出来。

Alpha newA1 = new Alpha(1.0, "a", null);  //no old Alpha
Alpha newA2 = new Alpha(2.0, "b", newA1); // newA1.y = bc as newA1 is Old alpha
Alpha newA3 = new Alpha(3.0, "c", newA2); // newA2.y = cb as newA2 is Old alpha

<强> SO:

 System.out.println(
                newA1.y //bc as written above
              + newA2.y //cb as written above
              + newA3.y //only c as newA3 is never oldAlpha so it contains only self value
              ); 

我希望这很清楚:)。