我不知道为什么,但这行代码给出NullPointerException
。我搜索了创建用户obj的数组。在Java中,但是,我找不到任何问题。
private State[] states;
.
.
.
private void initializeStates( )
{
states = new State[ stateNames.length ]; // Throws NullPointerException
for( int i = 0; i < stateNames.length; i++ )
{
states[i] = new State();
states[i].setName( stateNames[i] );
states[i].setColor( stateColors.getColor() );
}
} // End of initializeStates()
这是班级:
public class State
{
private String stateName;
private String color;
private boolean isStartState;
private boolean isFinalState;
State()
{
stateName = new String(); // Can this line cause nullPtrException?
color = new String(); // Can this line cause nullPtrException?
isStartState = false;
isFinalState = false;
}
public void setName( String name ){ stateName = name; }
public void setColor( String clr ) { color = clr; }
public void makeStart( ) { isStartState = true; }
public void makeFinal( ) { isFinalState = true; }
}
答案 0 :(得分:5)
如果此行抛出异常:
states = new State[ stateNames.length ]; // Throws NullPointerException
...然后问题是stateNames
是null
。你没有像其他任何代码那样做到这一点。
您尚未显示宣布或初始化stateNames
的位置,但您应该在下一步查看。
顺便说一下,这个:
stateName = new String();
......无缘无故地效率低下。只需使用空字符串文字:
stateName = "";
(或者更好的是,将适当的初始值作为构造函数参数。)