我有以下课程:
public class Transaction {
public String Type;
public double Amount;
public double Balance;
Transaction(String Type,double Amount,double Balance){
this.Type = Type;
this.Amount = Amount;
this.Balance = Balance;
}
public String toString(){
String s = " Type: "+ Type +"\n Amount: "+ Amount+ "\n Balance: "+Balance;
return s;
}
Run Code Online (Sandbox Code Playgroud)
这用于创建与我的主类的事务实例,所以我最终可以打印出长列表中的所有事务,如语句.
在我的主类帐户中,到目前为止我有这个代码:
public class Account {
private String name;
private double balance;
public double initDeposit;
protected ArrayList<Transaction>;
public Account(String name, double initDeposit){
this.balance =initDeposit;
this.name = name;
Transaction a = new Transaction("Creation",initDeposit,balance);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试在创建帐户时创建一个新事务并将其添加到ArrayList但我没有正确声明数组列表.我怎么能这样做?谢谢你的回复.
你忘了给它命名ArrayList.试试这个:
protected ArrayList<Transaction> transactions;
Run Code Online (Sandbox Code Playgroud)
遵循OO编程最佳实践,您应该使用接口类型而不是具体类来声明属性:
protected List<Transaction> transactions;
Run Code Online (Sandbox Code Playgroud)
另外,不要忘记在构造函数中实例化该属性:
transactions = new ArrayList<Transaction>();
Run Code Online (Sandbox Code Playgroud)
或者甚至更简单,如果您使用的是Java 7或更新版本:
transactions = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)