【问题标题】:Calling a string[] from another class is appearing null从另一个类调用字符串 [] 显示为空
【发布时间】:2012-03-20 08:33:27
【问题描述】:

我对编程有点陌生,所以我相信这是一个简单的答案。

基本上,在我的主要方法中,我想这样做:

...

wordtime = new LabelField("" + DataStored.words[0]);

...

现在在 DataStored 类中,我有: ...

public static String[] words;
{
    words = new String[2];

    words[0] = "Oil sucks!";
    words[1] = "Do you know that I can talk?";
}

...

所以每次我尝试编译程序时,它都会在主类中停止,说 DataStored.words[0] 为空。我怎样才能让它填充其他类的字段?提前谢谢!

【问题讨论】:

    标签: java arrays class


    【解决方案1】:

    您已经在那里编写了一个 initializer 块 - 每次您创建 DataStored 的新实例时都会执行它,但不是直到那个时候。我怀疑你想要:

    public static String[] words = { "Oil sucks!", "Do you know that I can talk?" };
    

    拥有这样的公共字段也是一个坏主意,至少对于常量以外的任何东西(在我看来,它包括不可变类型)。

    (我怀疑这在 compile 时间失败 - 这是一个 execution-time 失败。值得明确区别。)

    【讨论】:

      【解决方案2】:

      您在DataStored 的非静态 初始化块中初始化words。这意味着 words 在您实际构造 DataStored 的实例之前不会被初始化,这可能不是您想要的。

      你需要使初始化块静态,像这样:

      public static String[] words;
      static { // <---------------------
          words = new String[2];
      
          words[0] = "Oil sucks!";
          words[1] = "Do you know that I can talk?";
      }
      

      这将导致在DataStored 类加载时运行块。

      【讨论】:

        【解决方案3】:

        如果您想正确初始化words,您需要在一个静态块中进行,该块在类加载后立即运行。您使用的 initializer 块 仅在创建类的实例时运行,就在调用构造函数之前。所以当你调用DataStored.words[0] 时,初始化器还没有运行,words 仍然为空。

        public static String[] words;
        
        static
        {
            words = new String[2];
        
            words[0] = "Oil sucks!";
            words[1] = "Do you know that I can talk?";
        }
        

        或者你可以简单地这样做:

         public static String[] words = new String[]{"Oil sucks!","Do you know that I can talk?"};
        

        或者更短:

         public static String[] words = {"Oil sucks!","Do you know that I can talk?"};
        

        【讨论】:

          【解决方案4】:

          如果您在 Class DataStored 中定义初始化这两个变量的静态块。您可以访问它。

          类数据存储{

          public static String[] 单词;

          静态{

          words[0] = "Oil sucks!";
          words[1] = "Do you know that I can talk?";
          

          }

          }

          【讨论】:

            【解决方案5】:

            public static String[] 单词; { 词=新字符串[2];

            words[0] = "Oil sucks!";
            words[1] = "Do you know that I can talk?"; }
            

            如果您想将其用作初始化words 的方法,而不是声明字符串数组,则在方法头中的单词后添加括号并删除分号。

            【讨论】:

            • -1。您的代码与问题中的代码完全相同,只是有一些空格更改。
            • 我只是在引用他的代码。不改变它。我在评论中说明了他需要的改变。
            • public static String[] words() { words = new String[2]; words[0] = "Oil sucks!"; words[1] = "Do you know that I can talk?"; }
            • 您在那里完成的是让某人调用words() 来初始化words 静态字段。当字段可以自动静态初始化时,为什么要这样做?
            猜你喜欢
            • 2015-10-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-11-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多