您好,Java 中 C++ 中的静态变量相当于什么?

问题描述 投票:0回答:2
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 c++ recursion static
2个回答
0
投票

没有 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);
        }
    }
}

0
投票

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);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.