【问题标题】:How to add values into an array list from other classes?如何将值添加到其他类的数组列表中?
【发布时间】:2014-11-05 17:34:11
【问题描述】:

请原谅我,因为我还是 Java 的新手。我有 9 个不同的课程。 在我的帐户驱动程序中,我需要创建一个加载数据的方法,我可以在其中放入一些假数据。

我似乎不知道如何输入这些值,因为我的构造函数是:

public Account(Customer c,double b,Day d){
    cust = c;
    balance= b;
    dateOpened=d;
    }

public Customer(String last, String first)
{
    this.last = last;
    this.first=first;
    custNum = nextNum;
    nextNum++;
}

public Day(int yyyy, int m, int d) 
{  year = yyyy;
  month = m;
  day = d;
  if (!isValid()) 
     throw new IllegalArgumentException();
}

  public CheckingAccount(double mf,Customer c,double b,Day d){
    monthlyFee=mf;
}

 public SavingsAccount(Customer c,double b,Day d,double i){

    intRate=i;


}

 public SuperSavings(double mf,Customer c,double b,Day d,double m){
    minDeposit=m;


}

和我的 AccountDriver:

import java.util.ArrayList;


public class AccountDriver {

public static void main(String[] args){
    ArrayList<Customer> c = new ArrayList<Customer>();
ArrayList<Account> a = new ArrayList<Account>();
ArrayList<Day> d = new ArrayList<Day>();

    loadData(c,a,d);
    print(a);
}

public static void loadData(ArrayList<Customer> c,ArrayList<Account> a, ArrayList<Day> d) {

    a.add(new Account(new Customer("Sam", "Jones"),45000,new Day(2012,12,4)));

}

private static void print(ArrayList<Account> s) {
    for (int i=0;i<s.size();i++)
System.out.println(s.get(i).toString());
}

}

【问题讨论】:

  • 你想做什么?将这些类的所有实例放在同一个ArrayList 中?还是将它们放在不同的ArrayLists 中?

标签: java inheritance arraylist polymorphism loaddata


【解决方案1】:

您需要创建所有必要的实例:

Customer c = new Customer("John", "Doe");
Day day = new Day(2014, 9, 11);
Account account = new Account(c, 1000D, day);
// add the account
List<Account> accounts = new ArrayList<>();
accounts.add(account);

【讨论】:

    【解决方案2】:

    您必须传入与构造函数方法签名匹配的参数。这是一个例子:

    Customer customer = new Customer("Doe","John");
    double balance = 1000.0;
    Day day = new Day(1992,4,20);
    
    a.add(new Account(customer, balance, day));
    

    【讨论】:

    • 我认为 double 结尾需要一个 d 就像double balance = 1000.0d;
    【解决方案3】:
    Account account = 
        new Account( new Customer("first name","last name"), 10.0d, new Day(2014,9,11));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 2022-01-07
      • 1970-01-01
      • 2015-04-25
      相关资源
      最近更新 更多