为什么声明整数 Static 会导致我的代码出错?

Why does declaring an integer Static cause an error in my code?

我正在使用 Making a simple high-score system - Codecall 中的代码,但在使用时收到错误消息。导致问题的行在 HighScoreManager() class 内。

这是错误代码:

public String getHighscoreString() {
    String highscoreString = "";
    Static int max = 10; // this line gives an error

    ArrayList<Score> scores;
    scores = getScores();

    int i = 0;
    int x = scores.size();
    if (x > max) {
        x = max;
    }
    while (i < x) {
        highscoreString += (i + 1) + ".\t" + scores.get(i).getNaam() + "\t\t" + scores.get(i).getScore() + "\n";
        i++;
    }
    return highscoreString;
}

Static int max = 10;抛出

not a statement

使用小写 "s" (static) 抛出

illegal start of expression

如果我删除 Static 它会起作用。我不知道这是否会对代码产生重大影响。用小写的"s"也不行,大写的Static是网站上有代码的,所以我不知道为什么他们写的是大写的S。

您的代码中存在一处普遍错误和一处非法字段声明:

  1. 首先,一般来说:总是 static,而不是 Staticstatic 应该是小写的。 Java 否则不会将其识别为关键字。您可以阅读有关 case sensitivity in java here.

  2. 非法字段声明:我在你的HighscoreManager.class中删除了int max = 10;中的static关键字后,代码编译执行完美getHighscoreString()方法。

除了HighscoreManager.class,我还使用了website you referenced中的Main.classScore.classScoreComparator.class,没有改变。

为什么会这样?

您不能在方法中声明静态字段。默认情况下不允许。

您可以阅读有关该主题的 this post

输出为:

1.  Marge       300
2.  Lisa        270
3.  Bart        240
4.  Maggie      220
5.  Homer       100

not a statement 因为静态在 java 中什么都不是,但它是 static.

此外,您不能在每次调用函数时都生成一个 static 变量,而是直接在 class 中声明。这是因为它没有用 class 的对象实例化,而是最初附加了 class 并且可以通过一个点符号访问。(取决于它是否是私有的)。