這裏是第一類有人可以解釋這個代碼
公共類Number {
private static int Result;
public Number(int X){
if(X == 0){ return; }
Result += X;
Number another_number = new Number(X-1);
}
public static void Clear(){
Result = 0;
}
public static int getResult(){
return Result;
}
}
這裏是第二類 公共靜態無效的主要(字串[] args){
Number.Clear();
Number x = new Number(5);
System.out.println("The result is " + Number.getResult());
Number y = new Number(5);
System.out.println("The result is " + Number.getResult());
Number.Clear();
Number z = new Number(5);
System.out.println("The result is " + Number.getResult());
}
起初我以爲答案是:
The result is 9. (Because 10-1 is 9)
The result is 13. (Because 9+5 -1 is 13)
The result is 4. (Because 5-1 is 4).
但實際上答案是:
The result is 55
The result is 70
The result is 15
這難倒我。我知道我錯過了一些大概念,但我無法弄清楚。我已經和另外3個人交談過,他們也很難過。如果有人能幫助我們,那會很棒。
您應該逐個調試器中的代碼,看看實際發生了什麼。 –
您確定此代碼生成55,70,15嗎?我預計它會產生15,30,15。你是否複製/粘貼錯誤的東西?無論哪種方式,你對「10-1是9」等事物的推理完全不相干。代碼無處不在。代碼*正在做的是遞歸計數並將每個結果添加到靜態總數中。然後打印總計。 5 + 4 + 3 + 2 + 1是15.(當然,15 + 5 + 4 + 3 + 2 + 1是30.) – David
我期望它產生15,15和15.注意重置每次通話之間的靜態 – tddmonkey