简体   繁体   English

创建全局变量-Java

[英]Creating global variables - Java

I am getting a compiling error for this code: 我收到此代码的编译错误:

public class Matching {        
    public static int match = (int) Math.floor(Math.random()*cities.size()); //Error is here
}

I'm want to make "match" a global variable. 我想使“匹配”成为全局变量。

My compiling error is: 我的编译错误是:

"Illegal static declaration in inner class testingProgram.Matching modifier 'static' is only allowed in constant variable declarations “内部类testingProgram.Matching修饰符'static'中的非法静态声明仅在常量变量声明中允许

Usage of static non-final variable during initialization." 在初始化期间使用静态非最终变量。”

Don't know what the error means, nor do I know how to fix it. 不知道错误意味着什么,也不知道如何解决。

This happens because your Matching class is located inside another class called testingProgram , and is not static . 发生这种情况是因为您的Matching类位于另一个名为testingProgram类中,并且不是static

Java allows static fields inside an inner class only when the inner class itself is static . Java仅在内部类本身为static时才允许在内部类内部使用static字段。 You can fix this problem in several ways: 您可以通过以下几种方法解决此问题:

  • By making Matching a static inner class, 通过使Matching成为static内部类,
  • By making Matching a top-level class, or 通过Matching顶级课程,或
  • By making static int match final, ie final static int match 通过使static int match final,即final static int match

Create the variable in some static class (main, for example) and make sure it gets passed to the constructor of this class. 在某个静态类(例如main)中创建变量,并确保将其传递给此类的构造函数。 I don't know why you are doing this but the reason it's difficult is because it's not a good idea. 我不知道您为什么要这样做,但之所以困难是因为这不是一个好主意。 If you need to save the state of 'match' then give more information. 如果您需要保存“匹配”状态,请提供更多信息。

public static void main() {
    int match;
    Matching m = new Matching(match);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM