2012-03-01 26 views
2

我对编程有点新,所以我确信这是一个简单的答案。调用另一个类的字符串[]是显示为空

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

...

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

...

现在在DataStored I类有: .. 。

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

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

...

所以每次我尝试编译程序时,它都会停止在主类上,说DataStored.words [0]为空。我怎样才能让它从其他课程的领域填充?先谢谢你!

回答

4

你在非初始化wordsDataStored的静态初始化块。这意味着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类是加载要运行的块。

6

你写了一个初始化块有 - 这将是每次创建的DataStored一个新实例时执行,但时间不直到。我怀疑你想:

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

这也是一个坏主意,有这样的公共领域,至少比常量的任何其他(其中包括在我看来稳定的类型)。

(我怀疑这是在失败编译时间虽然 - 这是一个执行时间失败值得被明确的区别。)

1

如果要正确初始化words,则需要在静态块中执行该操作,该类会在加载类后立即运行。一个初始化块,只有在调用构造函数之前创建类的实例时才会运行。因此,当您拨打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?"}; 
1

如果定义静态初始化块在类DataStored这两个变量。你可以访问它。

类DataStored {

public static String [] words;

静态{

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

}

}

-1

公共静态字符串[]字; {words} = new String [2];

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

如果你想用这个作为一种方法在方法头初始化words,而不是宣布字符串的再加入parathesis数组话后,并删除分号。

+0

-1。你的代码与问题中的代码完全等价,只是有一些空白的改变。 – 2012-03-01 20:38:42

+0

我只是在引用他的代码。没有改变它。我在评论中陈述了他需要的改变。 – Avogadro 2012-03-02 01:44:35

+0

'public static String [] words(){words = new String [2]; words [0] =“Oil sucks!”; words [1] =“你知道我可以说话吗?”; }' – Avogadro 2012-03-02 02:06:30

相关问题