2016-09-24 70 views
2

任何人都可以解释这个程序的输出吗?为什么是第二个值7?Java递归函数技巧

无法理解递归函数调用go(this)

public class ThisIsTricky { 

    int state = 0; 

    public ThisIsTricky(int s) { 
     state = s; 
    } 

    public static void main(String[] args) { 
     ThisIsTricky obj1 = new ThisIsTricky(1); 
     ThisIsTricky obj2 = new ThisIsTricky(2); 

     System.out.println(obj1.go(obj1) + "" + obj2.go(obj2)); 
    } 

    int go(ThisIsTricky thisIsTricky) { 
     if (this.state == 2) { 
      thisIsTricky.state = 5; 

      go(this); 
     } 
     return ++this.state; 
    } 

} 

输出: -

2 7 

回答

3

要注意的重要一点是,state是一个成员变量,所以它不共享obj1obj2。每个都有自己的价值(分别为1和2)。

为什么obj2的输出为7?条件(this.state == 2)对于obj2是正确的,所以你递归到go(this)。现在条件不再成立,因为state已更改为5,因此state会增加。递归调用结束,您现在返回到调用函数(在go(this)之后)和state再次递增。因此,5 + 1 + 1 = 7。

+1

正确解释 – Ironluca

1

该程序的输出将出现为27(不含空格)。这是由于java在函数调用中传递了对象变量的地址。

  1. 第一2将是obj1.go(obj1)呼叫这将是OBJ1的状态值的增量的结果。
  2. 下输出将7obj2.go(obj2)被调用,并为OBJ 2的状态值是2触发if声明并更改状态值5。然后递归函数go(this)与原来的参数相同的地址再次呼吁。这次不调用if语句,函数只是返回一个递增值,即6。然后控件返回到原始函数,函数返回该值的增量,即7,并将其打印在输出中。
1

'OBJ1': '!1 = 2' '状态= 1',因此返回1 + 1 = 2

'OBJ 2' 是容易当你解开这个递归理解:

 
State = 2 so we enter the conditional clause: 
Set state=5 
Recursively call to 'go' 
    state is 5 and 5!=2. So skip conditional clause 
    increment state, state is now 5+1=6 
    return 6 
Back in the original call to 'go', increment state, state is now 6+1=7 
return 7 

因此,输出是27