Mon*_*lal 0 java null nullpointerexception
我想给一个名为State的类的每个子项赋值,而我有一个状态数组最初都为null,我在这里接收空指针引用:
//finding all the neighbor states of a given configuration
public State[] neighborStates(String config, int modeFlag){
State[] neighborStates=new State[7];
int i=0;
for (Operation o : Operation.values()){
neighborStates[i].config=move(config,o.name().charAt(0));
neighborStates[i].realCost++;
neighborStates[i].opSequence+=o.name();
neighborStates[i].heuristicCost=getHeuristicCost(neighborStates[i].config, modeFlag);
i++;
}
return neighborStates;
}
Run Code Online (Sandbox Code Playgroud)
我将代码更改为此但我还是获得了NPE:
public State[] neighborStates(String config, int modeFlag){
State[] neighborStates=new State[8];
int i=0;
for (Operation o : Operation.values()){
neighborStates[i] = new State(move(config,o.name().charAt(0)),neighborStates[i].realCost++,
getHeuristicCost(neighborStates[i].config, modeFlag), neighborStates[i].opSequence+=o.name());
//neighborStates[i].config=move(config,o.name().charAt(0));
//neighborStates[i].realCost++;
//neighborStates[i].opSequence+=o.name();
//neighborStates[i].heuristicCost=getHeuristicCost(neighborStates[i].config, modeFlag);
i++;
}
Run Code Online (Sandbox Code Playgroud)
类State定义为:
public class State {
public State(String config, int realCost, int heuristicCost, String opSequence){
this.config = config;
this.realCost = realCost;
this.heuristicCost = heuristicCost;
this.opSequence = opSequence;
}
Run Code Online (Sandbox Code Playgroud)
您需要State在neighborStates数组中实例化.您创建了一个包含7个插槽的阵列,但它们最初都是null.假设你有一个默认的构造函数,它应该看起来像,
for (Operation o : Operation.values()){
neighborStates[i] = new State();
// ...
Run Code Online (Sandbox Code Playgroud)
此外,neighborStates基于大小调整可能是一个好主意Operation.values()
State[] neighborStates = new State[Operation.values().length];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |