每当用户想要创建新帐户时,我该如何创建唯一对象?
例如,如果用户创建了一个帐户,我想要一个名为 acc1 的对象,那么如果用户创建了另一个帐户,我想要名为acc2的对象。
Account ac = new Account(input.nextInt(),0,0);
。这就是我需要它发生的地方。
我尽量保持代码尽可能简单,并且还注意到我对java很新,这是一个只是为了学习的个人项目。
System.out.println("Welcome to JAVA Bank");
System.out.println("____________________");
System.out.println("Plese Choose an Option: ");
System.out.println("");
System.out.println("(1) New Account");
System.out.println("(2) Enter Existing Account");
int choice = input.nextInt();
switch(choice){
case 1:
System.out.println("Please choose an Account ID#");
Account ac = new Account(input.nextInt(),0,0);
break;
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
private Date dateCreated;
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
this.dateCreated = new Date();
}
感谢您的帮助。
答案 0 :(得分:4)
如果您想要一种识别多个帐户的独特方式,或许可以使用HashMap。 HashMap存储每个键唯一的键值对。
创建一个类级变量来存储帐户:
Map<String, Account> accounts = new HashMap<String, Account>();
创建/添加帐户到HashMap:
case 1:
System.out.println("Please choose an Account ID#");
int accountID = input.nextInt(); //Get the requested ID
if (accounts.containsKey("acc"+accountID) //Check to see if an account already has this ID (I added acc to the start of each account but it is optional)
{
//Tell user the account ID is in use already and then stop
System.out.println("Account: " + accountID + " already exists!");
break;
}
//Create account and add it to the HashMap using the unique identifier key
Account ac = new Account(input.nextInt(),0,0);
accounts.put("acc"+accountID, ac);