gpt4 book ai didi

java - 将对象添加到 arrayList

转载 作者:行者123 更新时间:2023-12-01 18:52:25 25 4
gpt4 key购买 nike

我在用 Java 向 arrayList 添加对象时遇到问题。当我运行我的代码时,出现以下错误。这是我的两个文件的片段。如果有人指出我的错误,我将非常感激。谢谢,乔

House.addRoom(House.java:18)处的java.lang.NullPointerException House.(House.java:36)

//房间等级

  public Room () {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");

System.out.println("Enter description of room:");
description = scan.next();

System.out.println("Enter length of room:");
length = scan.nextDouble();

System.out.println("Enter width of room:");
width = scan.nextDouble();
}

//房屋等级

public class House {
private static ArrayList<Room> abode;

public void addRoom (){
abode.add(new Room ());
}
public House () {
idNum = ++internalCount;
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");

System.out.println("Enter address of house:");
address = scan.next();

System.out.println("Enter number of rooms:");
numRooms = scan.nextInt();

System.out.println("Enter type of house:");
houseType = scan.next();

for (int i=1; i<=numRooms; i++){
addRoom();
}
}
}

最佳答案

您需要初始化您的arraylist在向其中添加元素之前。可能在构造函数中初始化

private static ArrayList<Room> abode;

public House()
{
abode = new ArrayList<String>();
//rest of your code
}

顺便说一句,对接口(interface)进行编码比对实现进行编码始终是一个好习惯:

List<Room> abode = new ArrayList<String>();

关于java - 将对象添加到 arrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15407049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com