【问题标题】:How should I add this object to the array...?我应该如何将此对象添加到数组中......?
【发布时间】:2012-01-09 15:56:25
【问题描述】:

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

定义一个名为 Laboratory 的类,其中包含一组计算机。 数组的大小应该在构造函数中指定 实验室课。您的类应该包含用于添加 计算机到阵列。 (前面部分我必须用构造函数定义一个具有几个属性的计算机类)

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

【问题讨论】:

  • 你刚刚意识到你可以做到这一点......

标签: java arrays class methods


【解决方案1】:

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

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;
    }

}

【讨论】:

    【解决方案2】:

    您可以在数组中拥有一个包含当前计算机数的实例变量,然后使用它来添加计算机

    private int computerCount = 0;
    
    public void addComputer(Computer comp)
    {
        arrayName[computerCount] = comp;
        computerCount++;
    }
    

    【讨论】:

    • 你忘记增加计数了。
    • 并检查 ArrayOutOfBoundsException
    • 目前,每次都会覆盖数组的第一项。你需要维护一个索引指针。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2018-06-08
    相关资源
    最近更新 更多