2014-02-23 44 views
0

我需要做一个这个类的实例,但是当我尝试我得到一个NullPointerException。 你能告诉我为什么以及如何解决,我还是很新的。为什么我在创建我的类的新实例时遇到java.lang.NullPointerException?

public class NewTryPoints { 

private int[] pointX; 
private int[] pointY; 
private static final int topix = 5; 

public NewTryPoints(){ 
    setX(); 
    setY(); 
    } 

public void setX(){ 

    pointX[0] = 1; 
    pointX[1] = (int)Math.random() * (50 - 1) * topix; 
    pointX[2] = 2 + (int)(Math.random() * ((50 - 2) + 1)) * topix; 
}; 

public void setY(){ 

    pointY[0] = 1 * topix; 
    pointY[1] = 2 + (int)(Math.random() * ((50 - 2) + 1)) * topix; 
    pointY[2] = 1 * topix; 

}; 

public int[] getpointX() { return pointX; }; 
public int[] getpointY() { return pointY; }; 

} 

其他类

public class Main { 

public static void main(String[] args) { 
NewTryPoints points = new NewTryPoints(); 

    } 

} 
+0

你在哪一行得到NPE?提供一个堆栈跟踪! – Zavior

回答

1

您正在使用的引用pointX尖尖没有给他们分配内存,因此它们是空,一个NullPointerException异常升高。你应该先做..

public NewTryPoints(){ 
    pointX = new int[3]; 
    pointY = new int[3]; 
    setX(); 
    setY(); 
} 
0

你不会在所有初始化数组:

private int[] pointX; 
private int[] pointY; 

尝试访问这两个在空的设置方法的结果,因为他们做的不包含对数组对象的引用呢!

0

您必须在Java中使用它之前初始化数组。您设置setX的价值观和setY方法之前在构造

public NewTryPoints(){ 
    //initializing the arrays 
    pointX = new int[3]; 
    pointY = new int[3]; 
    setX(); 
    setY(); 
    } 

希望这有助于请初始化数组!

0

在您的构造函数中,您调用setX()setY(),这反过来为您的数组填充值。问题是您没有初始化这些阵列:

pointX = new int[5]; // 5 is just for the example 
pointY = new int[5]; 
0

您尚未初始化对数组的引用。这意味着,

private int[] pointX; 

相同

private int[] pointX = null; 

所以当你

pointX[0] = ... 

它抛出一个NullPointerException异常。

你可以看到这个的一种方法是在你的调试器中查看它。

最有可能你打算写

private int[] pointX = new int[3]; 
1

你还没有初始化数组。

在调用setx和sety之前,在构造函数中添加它。

pointX = new int[3]; 
pointY = new int[3]; 
相关问题