通过循环添加对象时,ArrayList不会展开

时间:2015-04-28 23:28:16

标签: java arraylist polymorphism

我认为可能存在多种错误,但基本上我希望每次循环在我的潜水员类中再次运行时添加一个Ship。但由于某种原因,我的toString方法只输出最新的一个或do while循环的最后一次迭代。我可以在必要时发布所有代码,但我认为问题出在这两个类中的一个。

发货类

import java.util.Scanner;


public class ShipDriver 
{


static Ship cS;
static Ship cargo;


public static void main(String[] args)
{
    System.out.println("----------------------Ship Company----------------------");
    String name, ans;
    int year, passenger = 0, ton = 0, oneTwo; 
    Scanner kb = new Scanner(System.in);
    ShipCompany sh = new ShipCompany();

    do
    {
        System.out.println("Enter the ship's name:");
        name = kb.next();

        System.out.println("Enter the " + name + " build year:");
        year = kb.nextInt();


        System.out.println("Enter 1 for cruise ship or 2 for a cargo ship");
        oneTwo = kb.nextInt();



        if(oneTwo == 1)
        {
            System.out.println("Enter the number of passengers for the " + name);
            passenger = kb.nextInt();
        }
        else
        {
            System.out.println("Enter the maximum capacity of the " + name);
            ton = kb.nextInt();
        }


        cS = new CruiseShip(name, year, passenger);
        cargo = new CargoShip(name, year, ton);
        sh.add(getInfo(oneTwo));
        System.out.println("Do you want enter another ship's information? y/n");
        ans = kb.next();

    }while(ans.equals("y") || ans.equals("Y") || ans.equals("Yes") || ans.equals("yes") );

    System.out.println(sh.toString());
    kb.close();
}
public static Ship getInfo(int num)
{
    if(num == 1)
    {
        return cS;
    }
    else 
        return cargo;

}
}

ShipCompany Class

import java.util.ArrayList;

public class ShipCompany 
{
static ArrayList<Ship> arr;
Ship ship = new CargoShip();
Ship ship2 = new CruiseShip();

public ShipCompany()
{
    arr = new ArrayList<Ship>();
}

public static void add(Ship o)
{
    arr.add(o);
}

public String toString()
{
    for(int i = 0; i < arr.size(); i++)
    {
        if(ShipDriver.getInfo() instanceof CargoShip)
        {
             return ship.toString();
        }
        else
             return ship2.toString();
    }
 }
}

如果您需要其他3个课程,我可以像我说的那样发布它们,但我非常确定问题可能出在我的toString方法或我的add方法上。我只是不确定如何解决它。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

当你调用CruiseShip或CargoShip的构造函数时,它也会调用超类构造函数,其中静态字段arr的旧值丢失。

答案 1 :(得分:0)

我认为这是因为cS和货物被宣布为静态油田。请将它们声明为main方法的局部变量(就在执行循环之前)并重构getInfo方法