如何生成顺序帐号?

时间:2014-05-17 21:49:54

标签: java

我正在制作一个银行帐户程序,对于我的构造函数,我希望它添加客户名称(它确实如此),我还希望它自动生成从1到n个客户添加的每个客户的帐号(其中它没有...),如果我有3个名字,当我将这些名称添加到我的“BankDataBase”类中的ArrayList时,它会为每个accNum打印num 3。

public class Customer
{
private final String fname;
private final String lname;


Customer(String fn, String ln)
{
    fname = fn;
    lname = ln;
}

public class Account
{

private Customer cust;
private int accNum = 0;
private double balance;

Account(Customer c)
{
    cust = c;
    balance = 0;
    accNum++;
}

public class DataBase
{

private Account accCust;
int getAcc = 0;

ArrayList<Account> chaseAccts = new ArrayList<>();

public void addAcct(Account me)
{
    accCust = me;
    chaseAccts.add(me);
}

public void display()
{
    for (int i = 0; i < chaseAccts.size(); i++)
    {

        System.out.println(chaseAccts.get(i).getAccount() + " " + accCust.getAccNum());
    }
}

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以静态跟踪分配的帐号,并为新帐户分配系列中的下一个号码。像

这样的东西
public class Account
{

    private static int nextAccoutNumber = 0;

    private Customer cust;
    private double balance;

    Account(Customer c)
    {
       cust = c;
       balance = 0;
       accNum = ++nextAccountNumber;
    }
}

您将新帐户添加到列表中,但您也将其存储在本地变量中。你在做什么:

System.out.println(chaseAccts.get(i).getAccount() + " " + accCust.getAccNum())

您每次都在写出相同accCust的accNum值。你需要写

System.out.println(chaseAccts.get(i).getAccount() + " " + chaseAccts.get(i).getAccNum());

由于您使用的是ArrayList<Account>类型的列表,您可以将整个循环写为:

public void display()
{
    for(Account account : chaseAccts) {
        System.out.println(account.getAccount() + " " + account.getAccNum());
    }
}

答案 1 :(得分:0)

您可以尝试制作静态变量

private static int accSeq = 0
private Customer cust;
private int accNum = 0;
private double balance;

Account(Customer C) {
    cust = c;
    balance = 0;
    accNum = ++accSeq;
}