使用构造函数初始化数组 - Java

Kar*_*ruw -2 java arrays constructor object

我有2个班:产品和房间.我希望用户能够说出数组的大小,创建一个Object Room并输入一个int.

public class Room{
  private int n;
  private int count = 0;
  Product [] space = new Product[n];

public Room(int n){
  this.n = n;
}
Run Code Online (Sandbox Code Playgroud)

为什么构造函数不使用输入n创建数组,我给他?我有什么想法我做错了吗?

Era*_*ran 10

数组在构造函数体之前初始化,当n仍然0(默认情况下)时,它获得一个0长度.

您需要在构造函数的主体中初始化它:

public Room(int n){
    this.n = n;
    this.space = new Product[n];
}
Run Code Online (Sandbox Code Playgroud)