2015-12-15 23 views
1

我对Java很新,所以我只是在练习一些我学到的东西,并且一直在制作一个存储客户帐户等的银行程序。这是我有一个类型为Customer的数组的帐户的开始,这是我创建的一个类,其中包含3个用户名,密码和帐号的参数。将元素存入数组,但在Java中有数组索引更新

我想让这个数组以这种方式存储所有的客户,就像你从方法“addAcc”中看到的一样。在这里,我将新客户对象作为第一个元素添加到客户类型数组中,但我不确定如何在NEXT数组索引中添加下一个客户,在下次调用此方法时如何更新索引以添加另一个客户用户?还是有另一种方式去解决这个问题?

public class Bank { 
     private double interest_rate = 1.01; // interest rate 
     private Customer[] accounts = new Customer[1000]; // array to store accounts 

    // adds new customer 
    public void addAcc (String user, String pass, int accNum) { 
     Customer accID = new Customer(user,pass,accNum); 
     this.accounts[0] = accID; 
    } 
+1

为什么不使用'ArrayList'而不是Array?所以你不需要麻烦数组的容量。 –

+0

我知道这是一种可能性,但是对于一个数组,没有办法以某种方式编写它,所以当我下一次添加另一个元素时,它将它添加到下一个索引而不是重写第一个元素?即使我最终使用ArrayList – Darkphoton

+0

,我仍然想学习这一点。您可以添加一个实例变量并将其初始化为零,并且每次调用addAcc时,都会将其加1。 – Rodolfo

回答

2

只需创建一个计数器变量,这将保持跟踪有多少客户已经加入

public class Bank { 
    private double interest_rate = 1.01; // interest rate 
    private Customer[] accounts = new Customer[1000]; // array to store accounts 
    private int counter=0; 

// adds new customer 
public void addAcc (String user, String pass, int accNum) { 
    Customer accID = new Customer(user,pass,accNum); 
    this.accounts[counter++] = accID; 
} 
+0

好的,但是这个柜台什么时候增加?每次我调用这个方法来添加一个新成员时,用“counter ++”是否会增加1? – Darkphoton

+0

是的,你第一次调用它时,它会将客户存储在0索引处,并且在0索引处存储之后它将增加1,下一次你将添加时,它将存储在索引1处,然后它将增加1个值2 –

1

更好的解决方案是使用ArrayList

public class Bank { 
    private double interest_rate = 1.01; 
    private List<Customer> accounts = new ArrayList<>(); 

    public void addAcc (String user, String pass, int accNum) { 
     Customer accID = new Customer(user, pass, accNum); 
     this.accounts.add(accID); 
    } 
} 

该解决方案是因为数组列表根据需要动态调整自身大小。使用数组的第一个解决方案时,当达到数组的容量时会出现错误。

为了记录在案,作为劣等的替代,你可以保持一个计数:

public class Bank { 
    private double interest_rate = 1.01; // interest rate 
    private Customer[] accounts = new Customer[1000]; // array to store accounts 
    private lastIndex = -1; 

    // adds new customer 
    public void addAcc (String user, String pass, int accNum) { 
     Customer accID = new Customer(user,pass,accNum); 
     this.accounts[++lastIndex] = accID; 
    } 
} 
+0

好的解释谢谢 – Darkphoton

0

最好是使用一个集合,而不是一个数组。可能是一个ArrayList 但是如果你仍然喜欢使用数组并继续,那么你必须检查下一个数组元素为空,并将新对象添加到该数组中。为此,您可以每次都经过该阵列,或者在添加帐户时具有索引并更新该索引

例如,

public class Bank { 
     private static nextIndex = 0; 
     private double interest_rate = 1.01; // interest rate 
     private Customer[] accounts = new Customer[1000]; // array to store accounts 

    // adds new customer 
    public void addAcc (String user, String pass, int accNum) { 
     Customer accID = new Customer(user,pass,accNum); 
     this.accounts[nextIndex++] = accID; 
    }