無法弄清楚這一點,我創建了一個簡單的類來保存x和y整數。在另一個類中,我有一個叫做「ords」的全局座標數組。在我的循環中,我添加了座標。在我的getaction方法中嘗試使用座標類中的方法getX()和getY()時,我得到一個空指針異常。我確信這些對象不是空的,但我仍然無法弄清楚什麼是錯誤的。任何幫助讚賞。Java - NullPoinerException對象數組
import java.util.*;
import org.w2mind.net.*;
import java.io.Serializable;
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
int currentX;
int currentY;
//====== Mind must respond to these methods: ==========================================================
// newrun(), endrun()
// getaction()
//======================================================================================================
public void newrun() throws RunError
{
}
public void endrun() throws RunError
{
}
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++)
{
for(int z = 0; z < 12; z++)
{
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
}
else if(surroundings[z][i]==4){
ords[n]= new Coordinates(z,i);
n++;
}
System.out.print(z+" , "+i+": "+surroundings[z][i]);
System.out.println();
counter++;
}
}
}
public Action getaction (State state)
{
String s = state.toString();
String[] x = s.split(",");
int act =MinerWorldUpdated.NO_ACTIONS;
int counter = 0;
int [] surround = new int [192];
//in this way user will have ability to see what surrounds him
for(int i = 11; i < 203; i++)
{
surround[counter] = Integer.parseInt(x[i]);
counter++;
}
formTwoDimmensional(surround);
int [] response = new int [x.length];
for(int i = 0; i < x.length; i++)
{
response[i] = Integer.parseInt (x[i]);
}
System.out.println("Current position: "+currentX+" ,"+currentY);
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
if(coalX != 0 && coalY !=0)
{
if(coalX>currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
else if(coalX<currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
}
String a = String.format ("%d", act);
return new Action (a);
}
}
class Coordinates implements Serializable
{
private int x;
private int y;
public Coordinates(int x1, int y1)
{
x=x1;
y=y1;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
錯誤如下: 顯示java.lang.NullPointerException 在ConorsMind.getaction(ConorsMind.java:146)
該錯誤是由以下兩行詞幹:
int coalX=ords[0].getX();
int coalY=ords[0].getY();
我打電話給formTwoDimensional(),它的工作完美,ords對象正在成功創建nd不爲null,因爲使用System.out.println(ords [n] .getX())進行測試時,將放置在我的else if(surround [z] [i] == 4)塊中時會打印預期結果。
請指出您在哪裏得到異常。 – Thilo
分享你的堆棧跟蹤。 – Smit
請發佈異常的堆棧跟蹤。 –