当我尝试用函数中的对象填充数组时,即使在主函数中事先声明了数组,也总是会出错。我也是OOP的初学者。
这是我的Point课:
public class Point {
private int positionX;
private int positionY;
public Point(int positionX, int positionY) {
this.positionX = positionX;
this.positionY = positionY;
}
public int getPositionX() {
return positionX;
}
public void setPositionX(int positionX) {
this.positionX = positionX;
}
public int getPositionY() {
return positionY;
}
public void setPositionY(int positionY) {
this.positionY = positionY;
}
}
这是我的主班:
public class Main {
public static void setupPointArray(Point ptArr[]) {
ptArr = new Point[] {new Point(2, 3),
new Point(4, 1),
new Point(6, 2)};
}
public static void main(String[] args) {
Point pointArray[] = new Point[3];
setupPointArray(pointArray);
System.out.println(pointArray[0].getPositionX() + pointArray[0].getPositionY());
System.out.println(pointArray[1].getPositionX() + pointArray[1].getPositionY());
System.out.println(pointArray[2].getPositionX() + pointArray[2].getPositionY());
}
}
但是控制台出现错误。
Exception in thread "main" java.lang.NullPointerException
at fr.antonin.point.Main.main(Main.java:15)
答案 0 :(得分:0)
您正在修改局部变量,即形式参数。它不会影响实际参数。
public static void setupPointArray(Point ptArr[]) {
ptArr = new Point[] {new Point(2, 3),
new Point(4, 1),
new Point(6, 2)};
}
您可以通过返回创建的数组或填充传递的原始数组来解决此问题。例如:
public static Point[] setupPointArray() {
return new Point[] {new Point(2, 3),
new Point(4, 1),
new Point(6, 2)};
}
或者,如果您确定其长度,则可以填充传递的数组:
public static void setupPointArray( Point[] ptArr ) {
ptArr[0] = new Point(2, 3);
ptArr[1] = new Point(4, 1);
ptArr[2] = new Point(6, 2);
}