【问题标题】:Object oriented design - working with arrays面向对象的设计——使用数组
【发布时间】:2015-04-13 11:29:27
【问题描述】:

我正在此链接中处理相同的任务:

Storing User Input into an Array

我已经编写了数组和所有内容,但是我想使用对象和方法来设置它,但是我正在努力掌握如何去做?

有没有什么办法可以将船只添加到某种“等待名单”中,并在找到可用空间后添加?最后,我如何将任何运动/运动时间“记录”到文本文件中?

任何帮助都将如此感激。谢谢你

【问题讨论】:

  • 欢迎来到 SO Caitlin!请参阅this post 了解有关提问的指南。在这种特定情况下,您需要展示您已经尝试过的内容并解释为什么它不起作用。
  • 给我们看一些代码,并要求一些更具体的东西,因为这太宽泛了
  • 在思考面向对象时,一个好的起点是命名作业所涉及的不同“事物”。每个“事物”通常被翻译成一个类,不同类型的“事物”被翻译成子类,最后通过变量来表达“事物”之间的关系。从正文的第一段开始,提到了以下“事物”:港口、码头、船舶、空间。这些都将是类。此外,船和太空都分为“小型”、“中型”和“大型”,它们将是子类。我会让你解决关系,因为评论充分

标签: java arrays object methods text-files


【解决方案1】:

您可以使用 ArrayList 来帮助您:

import java.util.ArrayList;
public static void main(String[] args) {
    ArrayList<Ship> shipList = new ArrayList<Ship>();
    shipList.add(aShip); //adds a new ship to the shipList
}

它的作用是创建一个 Ship 类型的 ArrayList(我假设您正在为您的船只使用一个名为 Ship 的类),您可以在其中存储等待的船只。一旦您的码头中有可用空间,您就可以遍历您的 ArrayList,直到找到适合开放空间的第一艘船,然后用船填充该开放空间:

for (Ship waitingShip : shipList) {
    if (waitingShip.size() <= freeSize) {
        // freeSize is the size of the berth that was opened up as an integer
        shipList.remove(waitingShip); // Removes the waitingShip from shipList
        // Add code here to add the waitingShip to your dock
        break; //Makes sure you only add one new ship to your dock by cutting off the for loop
    }
}

这假设你的 Ship 类有一个方法 size() 可以告诉你你的船的大小。

【讨论】:

    【解决方案2】:

    要使用对象和方法,您可能需要创建 3 个需要一系列船对象的不同码头对象 所以像这样的

    public class dock{
       myBoats[];
       void dock(boat[] boats){
             myBoats= Arrays.copyOf(boats,boats.length);
       }
       public boat getBoats(){return myBoats;}
    
    
    }
    

    船类应该是这样的

    public class boat{
    int mySize;
        void boat(int inSize){
    mySize = inSize;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 2018-02-04
      相关资源
      最近更新 更多