2013-08-19 34 views
0

嗨,你可以请清除我的疑惑,下面的程序。输出结果为2 7,但根据我的理解,它是2,6为什么go方法要多加一个额外的时间,并且计数递增为7。交付Java程序

class Handed { 
    int state = 0; 
    Handed(int s) { 
     state = s; 
    } 

    public static void main(String... hi) { 
     Handed b1 = new Handed(1); 
     Handed b2 = new Handed(2); 
     int t1 = b1.go(b1); 
     int t2 = b2.go(b2); 
     System.out.println(t1 + " " + t2); 
     //System.out.println(b1.go(b1) + " " + b2.go(b2)); 
    } 

    int go(Handed b) { 
     if(this.state == 2) { 
      b.state = 5; go(this); 
     } 
     int t3 = ++this.state; 
     return t3; 
    } 
} 

回答

0

此行是在

int t3 = ++this.state; 

第一次做+1,当你调用

go(this) 

然后

this.state 

是6.然后你做

int t3 = ++this.state; 

后再次IF statment

然后this.state是7

+0

谢谢,我明白了。在日食去(这)被调用后计数是6,而不检查条件,因此我有疑问。 – rama

0

++this.state在返回后执行两次,一次在go(this)和一次。

+0

。该方法应该返回值right.please解释。 – rama

+0

在方法调用go(this), 中,变量'state'在返回该值后不会返回,而是通过代码再次递增状态变量并返回递增值,即7返回该值,即7。 – Kishore

+0

请getvote如果我的回答帮助你 – Kishore

0

表达++ this.state递增1状态,因此它得到7

+0

谢谢,我明白了。 – rama

1

当你调用b2.go(b2);,内go方法变量bthis都是相同的。所以go(this)会增加state一次,然后它又回到int t3 = ++this.state;线,并再次增加state

+0

是的,我明白了。谢谢 – rama

0

当你在b2上调用“go”时,两次调用“go”,因为当state = 5时,if语句触发。这会导致状态在您传递的变量和您从中调用方法的变量中都变为6。

“走出去”是,如果再次挡在第二份声明中调用,但由于状态不是5,你只返回6 + 1,为什么后数为6被执行一次是7

+0

谢谢,我明白了 – rama