我不确定哪种方法不起作用。当我从addSavingsAccount创建帐户时,一切正常,但是当我想打印出来自两个类的信息时,它会输出name和pNr,但会显示所有客户端的第一个帐号。这有什么问题?
//this works fine
public int addSavingsAccount(long pNr){
for(int i = 0; i < customerlist.size(); i++)
{
if(customerlist.get(i).getPCode() == pNr)
{
Customer customer = customerlist.get(i);
customer.addAccount(pNr);
return account.getAccountId();
}
}
return -1;
}
//but this don't
public String infoAccount(long pNr, int accountId)
{
String info = "";
for(Customer customer : customerlist) {
if(customer.getPCode() == pNr) {
this.customer = customer;
ArrayList<SavingsAccount> accounts = customer.getAccount();
for (SavingsAccount account : accounts) {
this.account = account;
if (account.getAccountId() == accountId){
info = account.toString();
}
}
}
}
return info;
}
//this was my first try of printing out:
public String infoAccount(long pNr, int accountId)
{
String info = "";
for(Customer customer : customerlist)
{
if(pNr == customer.getPCode())
{
for(SavingsAccount account : accounts)
{
if(accountId == account.getAccountId())
{
info = "Personnummer: " + pNr + "\nKontonummer: " + accountId
+ "\nSaldo: " + amount + "\nRänta: " + SavingsAccount.RATE;
}
}
}
}
return info;
}
//the methods in Customerclass
public void addAccount(long pNr){
accounts.add(new SavingsAccount());
}
public ArrayList<SavingsAccount> getAccount(){
return accounts;
}
//methods from SavingsAccount
public int getAccountId(){
return accountCount++;
}
public String toString(){
String infoAccount = "\tKontonr: " + accountId + "\tKontotyp: " + accounttype +
"\nSaldo: " + balance + "\tRäntesats: " + RATE;
return infoAccount;
}
答案 0 :(得分:0)
我不确定我是否看到了足够的代码,但您似乎正在尝试进行设置,以便每个account
都有一个帐户ID。但是,您的getAccountId
方法在每次调用时都会返回不同的值,即使在同一SavingsAccount
上调用时也是如此,因为每次调用时它都会递增一个计数器调用。
您需要做的是在accountId
中声明SavingsAccount
之类的实例成员,并在创建新的SavingsAccount
时设置它:
accountId = accountCount++;
是您唯一想要使用++
的地方。然后,getAccountId()
将返回实例成员,而不会增加任何内容。