Java 如何将此对象添加到数组。。。?
这是一道过去的考试题,重点是数组,问题如下: 定义一个名为Laboratory的类,该类包含一组计算机。 数组的大小应该在构造函数中指定给 实验课。您的类应该包含用于添加 将计算机连接到阵列。 (前面的部分我必须定义一个计算机类,该类包含两个具有构造函数的属性) 所以我知道如何完成前两部分,构造函数中指定的类和大小。Java 如何将此对象添加到数组。。。?,java,arrays,class,methods,Java,Arrays,Class,Methods,这是一道过去的考试题,重点是数组,问题如下: 定义一个名为Laboratory的类,该类包含一组计算机。 数组的大小应该在构造函数中指定给 实验课。您的类应该包含用于添加 将计算机连接到阵列。 (前面的部分我必须定义一个计算机类,该类包含两个具有构造函数的属性) 所以我知道如何完成前两部分,构造函数中指定的类和大小。 第三部分(关于方法)我该怎么做?假设您已经编写了创建数组的构造函数: class Laboratory { private Computer[] computers;
第三部分(关于方法)我该怎么做?假设您已经编写了创建数组的构造函数:
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;
}
}
班级实验室{
专用计算机[]台计算机;
私有int nextIndex=0;
公共计算机(计算机公司){
//如果用户
//尝试添加太多计算机。您可能希望
//通过检查nextIndex
假设您已经编写了创建数组的构造函数:
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;
}
}
班级实验室{
专用计算机[]台计算机;
私有int nextIndex=0;
公共计算机(计算机公司){
//如果用户
//尝试添加太多计算机。您可能希望
//通过检查nextIndex
您可以拥有一个实例变量,其中包含阵列中计算机的当前计数,然后使用此变量添加计算机
private int computerCount = 0;
public void addComputer(Computer comp)
{
arrayName[computerCount] = comp;
computerCount++;
}
您可以拥有一个实例变量,该变量包含阵列中当前计算机的计数,然后使用该变量添加计算机
private int computerCount = 0;
public void addComputer(Computer comp)
{
arrayName[computerCount] = comp;
computerCount++;
}
您忘记增加计数。如果要立即检查ArrayoutOfBoundsException,则每次都会覆盖数组的第一项。您需要维护一个索引指针。您忘记了增加计数。如果要检查ArrayoutOfBoundsException,则每次都会覆盖数组的第一项。你需要维护一个索引指针。你刚刚意识到你可以做到…你刚刚意识到你可以做到。。。