在java中对数组使用get和set方法
我的java任务的一部分要求我使用set方法将细节输入到数组中。到目前为止,我有以下方法来设置细节在java中对数组使用get和set方法,java,arrays,get,set,Java,Arrays,Get,Set,我的java任务的一部分要求我使用set方法将细节输入到数组中。到目前为止,我有以下方法来设置细节 public void setCanopy(String uniqueRef, String modelName, int width, int height, int depth, int crewToBuild, double timeToBuild, double trailerLength, String available) { this.uniqueRef = uniqueRe
public void setCanopy(String uniqueRef, String modelName, int width, int height, int depth, int crewToBuild, double timeToBuild, double trailerLength, String available)
{
this.uniqueRef = uniqueRef;
this.modelName = modelName;
this.width = width;
this.height = height;
this.depth = depth;
this.timeToBuild = timeToBuild;
this.available = available;
this.crewToBuild = crewToBuild;
this.trailerLength = trailerLength;
}
只要该方法只用于向构造函数输入细节,它就可以正常工作,但当我尝试将其用于数组时,会得到一个NullPointerException
稍后我还必须使用get方法显示这些详细信息。我使用下面的方法来显示这些,但同样,它只在我使用构造函数时有效
public static void displayCanopyDetails(Canopy c)
{
System.out.println("Canopy reference number: " + c.getUniqueRef() + "\nCanopy model name: " + c.getModelName() +
"\nCanopy Dimensions (cm) - Width: " + c.getWidth() + " Height: " + c.getHeight() + " Depth: " + c.getDepth() +
"\nCrew to build: " + c.getCrewToBuild() + "\nTime to build canopy (minutes): " + c.getTimeToBuild() +
"\nTrailer Length: " + c.getTrailerLength() + "\nAvailability: " + c.getAvailable());
}
如果您能帮助这些设备使用阵列,我们将不胜感激。谢谢
我的主要方法是
tentDetails(c[0]);
调用该方法的
public static void tentDetails(Canopy c1,)
{
c1.setCanopy("CAN123", "Model1", 500, 200, 500, 5, 15, 10, "Available");
}
NullPointerException错误发生在它尝试运行此方法时。当您声明数组时,它会为对象创建一个空“包”,但不会创建对象本身。当您在此数组中的对象上使用方法时,会得到NullPointerException,因为该对象为null。在首先创建对象之前,不能在对象上执行方法。例如:
Canopy[] canopy=new Canopy[5]; //Creates a 'storage' for 5 Canopy objects
System.out.println(Canopy[0]); //Prints null and throws NPE if you execute method
Canopy[0]=new Canopy(); //Create new Canopy object and insert it in the array
System.out.println(Canopy[0]); //Not null anymore - you can execute methods
Canopy[0].setCanopy("CAN123", "Model1", 500, 200, 500, 5, 15, 10, "Available"); // works fine
在Java中,规则是当您创建一个数组时,它的元素接收默认值。对象的默认值为null,因此最初数组中的每个元素都为null。您必须显式地实例化树冠对象,如下所示:
for (int i = 0; i < c.length; i++) {
c[i] = new Canopy();
}
for(int i=0;i
在此之后,您可以安全地对数组的每个元素调用tentDetails()方法。不起作用的代码在哪里?您的意思是:“但是当我尝试将其用于数组时,会得到一个NullPointerException”?您需要使用构造函数,因为否则不会创建对象。如果使用数组,例如Canopy[]Canopy=newcanopy[5];然后,Canopy[1].object=5将获得null指针,因为数组为您提供了对象存储,但初始化数组不会在其中创建对象。它们是空的。如果您选中Canopy[1],则它为空。我已更新帖子,以显示尝试向数组输入详细信息的方法。这就是发生NullPointerException的地方。