我在玩 java,在使用自定义构造函数时遇到了问题。
当我开始我的程序时,主文件包含这样一行:
Word input = new Word(word);
word 的构造函数如下所示:
public Word(String s){
wordArray = s.toCharArray();
protocol = new Protocol(wordArray.length);
}
协议(protocol)看起来像这样:
public Protocol(int length)
{
letterList[0] = 'a';
letterList[1] = 'b';
letterList[2] = 'c';
letterList[3] = 'd';
letterList[4] = 'e';
letterList[5] = 'f';
letterList[6] = 'g';
letterList[7] = 'h';
letterList[8] = 'i';
letterList[9] = 'j';
letterList[10] = 'k';
letterList[11] = 'l';
letterList[12] = 'm';
letterList[13] = 'n';
letterList[14] = 'o';
letterList[15] = 'p';
letterList[16] = 'q';
letterList[17] = 'r';
letterList[18] = 's';
letterList[19] = 't';
letterList[20] = 'u';
letterList[21] = 'v';
letterList[22] = 'w';
letterList[23] = 'x';
letterList[24] = 'y';
letterList[25] = 'z';
wordLength = length;
for(int i=0;i<wordLength*2-1;i++)
{
display[i] = '_';
i++;
display[i] = ' ';
}
}
我在我的主文件中构造 word
的行得到一个 NullPointerException
,然后是 protocol
。
我已经对代码进行了试验,并注意到如果我不在 word
中调用 protocol
的构造函数,那么构建会在该点之后成功,但我需要协议(protocol)还要稍后构建,所以它仍然存在问题。
我不能在另一个构造函数中调用一个构造函数吗?有人对可能发生的事情有任何想法吗?
如果您需要更多说明,请告诉我!
最佳答案
Am I not allowed to call a constructor within another constructor?
不,您绝对可以这样做。
Anyone have any ideas on what may be going on?
显然,word
在传递给 Word
构造函数时为 null
:
Word input = new Word(word);
关于Java 构造函数和空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14555708/