每当用户想要创建一个新帐户时,我该如何创建一个唯一的对象?
例如,如果用户创建了一个帐户,我想要一个名为acc1的对象,那么如果用户创建其他帐户,我则想要名为acc2的对象。CCD_ 1。这就是我需要它发生的地方。
我试着让代码尽可能简单,同时也注意到我对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();
}
感谢您的帮助。
如果您想要一种独特的方式来识别多个帐户,那么可以使用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);