我的功能中意外输出

时间:2013-04-13 22:01:55

标签: java

public class Backhand {
    int state = 0;

    Backhand(int s) {
        state = s;
    }

    public static void main(String... hi) {
        Backhand b1 = new Backhand(1);
        Backhand b2 = new Backhand(2);
        System.out.println( b2.go(b2));
    }

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

当它运行时,它输出7.我认为++this.state;应该在方法go中执行一次,输出应该是6.有人可以解释这里发生了什么吗?

2 个答案:

答案 0 :(得分:1)

++this.state更改为this.state++,效果很好。

答案 1 :(得分:1)

你得到7的原因是因为你在go(this)方法中调用了go,所以最后,state会增加两倍。