使用ArrayList.get()API超出边界错误,通过索引值访问单个元素?

时间:2017-03-21 17:06:30

标签: java class

    roomArray.add(new Room(bed, kitchen, accessible, coffee, roomNumber));
    bookingReport();

}

public  void bookingReport()
{
    System.out.println(roomArray.get(4));
}

我想要打印用户输入的roomNumber,但是我收到了一个越​​界错误。有什么问题?使用get(4)索引4处的值,应返回roomNumber。

1 个答案:

答案 0 :(得分:0)

除非您添加了其他Room个对象,否则在此代码roomArray中看起来只有一个Room对象是使用此创建的 - new Room(bed, kitchen, accessible, coffee, roomNumber)

如果你尝试roomArray.get(0),你可能会得到你想要的那个房间,但是你需要一个访问方法来获得roomNumber

基本上在Room课程中:

public class Room
{
    private int roomNum;

    //I'm guessing what your constructor looks like based on your code, but I don't know the types
    public Room(boolean hasBed, String roomName, boolean isAccessible, boolean hasCoffee, int roomNumber)
    {
        roomNum = roomNumber;
    }

    //Here is your accessor method
    public int getRoomNumber()
    {
        return roomNum;
    }
}

然后在您的调用代码中,您可以使用以下代码访问它:

System.out.println(roomArray.get(0).getRoomNumber());