[英]Java How do I create a unique object name?
每次用戶想要創建新帳戶時,我將如何創建唯一對象?
例如,如果用戶創建一個帳戶,我想要一個名為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();
}
感謝您的幫助。
如果您想要一種識別多個帳戶的獨特方式,或許可以使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.