问题
I'm not sure which one of my methods that's not working. When i create accounts from addSavingsAccount everything is working fine, but when I want to print out the info from two classes it prints name and pNr but shows the first accountnumber to all clients. What's wrong with this?
//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;
}
回答1:
I am not sure I see enough code, but it looks like you're trying to set things up so that each account has an account ID. However, your getAccountId method is going to return a different value each time it's called, even when called on the same SavingsAccount, because it will increment a counter each time it's called.
What you need to do is to declare an instance member such as accountId in the SavingsAccount, and set it when a new SavingsAccount is created:
accountId = accountCount++;
That is the only place you want to use the ++. Then, getAccountId() would return the instance member, without incrementing anything.
来源:https://stackoverflow.com/questions/23523820/creating-a-method-from-calling-two-classes-in-java