static long sum(int n, long total) {
"static" boolean exitConditionMet = false;
if(n == 1) {
exitConditionMet = true;
return 1;
} else {
return total + sum(n-1, total);
}
}
如果这个变量为真,我需要执行不同的代码。并且它的地址对于所有递归调用都不应该改变。我的代码不同,但我提供了这个作为示例,请忽略错误,这只是为了理解我的问题。
您可以建议使用参数,但我不想要这个选项。
是否可以使用Java来实现这一点?我希望我解释清楚了。
我尝试了chatgpt和另一个接听平台。我期待一个等效的关键字
没有 Java 关键字允许您将局部变量声明为静态变量。 Java 中最接近 C++ 的是:
class Test {
static boolean exitConditionMet = false;
static long sum(int n, long total) {
if (n == 1) {
exitConditionMet = true;
return 1;
} else {
return total + sum(n-1, total);
}
}
}
Java 中的静态变量必须在类级别声明,而不是在方法内声明。
public class StaticKeywordExample {
private static int count = 0; // static variable
public static void printCount() { // static method
System.out.println("Number of Example objects created so far: " + count);
}
}