【问题标题】:Using get and set methods with arrays in java在java中对数组使用get和set方法
【发布时间】:2015-04-29 11:26:48
【问题描述】:

我的 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 = 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"?
  • 你需要使用构造函数,否则没有创建对象。如果您使用数组,例如 Canopy[] canopy=new Canopy[5];然后 Canopy[1].object=5 你得到 NullPointer 因为数组为你提供了对象存储,但初始化数组不会在里面创建对象。它们是空值。如果你检查 Canopy[1] 它是空的..
  • 我已更新我的帖子以显示尝试将详细信息输入数组的方法。这是 NullPointerException 发生的地方。

标签: java arrays get set


【解决方案1】:

当您声明数组时,它会为对象创建一个空的“包”,但它不会自己创建对象。当您对该数组中的对象使用方法时,您会得到 NullPointerException,因为该对象为空。在首先创建对象之前,您不能在对象上执行方法。例如:

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

【讨论】:

    【解决方案2】:

    在 Java 中,规则是当你创建一个数组时,它的元素接收默认值。 Object 的默认值为 null,因此最初数组中的每个元素都是 null。您必须像这样显式实例化 Canopy 对象:

    for (int i = 0; i < c.length; i++) {
        c[i] = new Canopy();
    }
    

    之后,您可以安全地对数组的每个元素调用 tentDetails() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多