gpt4 book ai didi

java - 我应该如何将此对象添加到数组中...?

转载 作者:行者123 更新时间:2023-12-02 00:32:04 25 4
gpt4 key购买 nike

这是一个过去的考试题,重点关注数组,问题如下:

定义一个名为 Laboratory 的类,其中包含一组计算机。数组的大小应该在构造函数中指定实验课。你的类应该包含添加方法计算机到阵列。(早期我必须使用构造函数定义一个具有几个属性的计算机类)

所以我知道如何执行前两部分,即构造函数中指定的类和大小。我将如何完成第三部分(关于方法)?

最佳答案

假设您已经编写了创建数组的构造函数:

class Laboratory {

private Computer[] computers;
private int nextIndex = 0;

public void addComputer(Computer comp) {
// throws an ArrayOutOfBoundsException if the user
// tries to add too many Computers. You might want to
// do something else by checking that nextIndex < computers.length
computers[nextIndex] = comp;
nextIndex += 1;
}

}

关于java - 我应该如何将此对象添加到数组中...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8791220/

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