2013-12-17 35 views
1

我目前使用散列圖存儲有關當前帳戶的信息。檢查HashMap密鑰是否存在時出錯

以下是我有一個方法:

HashMap<String, Account> account = new HashMap<String, Account>(); 
    if (Account.validateID(accountID)) { 
     System.out.println("Account ID added"); 
     Account a = new Account(cl,accountID, sortCode, 0); 
     account.put(accountID, a); //add to HashMap  
    } 

這似乎很好地工作。然後,在另一種方法,我有:

public void enterTransaction() 
{ 
    String tAccountID = JOptionPane.showInputDialog(this, 
    "Enter valid accountID", "Add Account", 0); 
    System.out.println("Check if accountID exists: " + account.containsKey(tAccountID)); //testing if accountID exists - currently not working 
    Date currentDate = new Date(); 
    System.out.println("Date and time of transaction: " + currentDate); //prints the date and time of transaction 

} 

基本上,我試圖讓這個當我去進入一個交易,它會檢查已輸入的交易帳戶ID等於從的AccountID HashMap(關鍵字)。

我嘗試使用enterTransaction()的線6,以檢查它是否存在。然而,即使當我知道我已經同時輸入了相同的accountID時,它似乎並不工作,並總是說「錯誤」。我也嘗試使用此聲明:

System.out.println(account.get(accountID)); 

這似乎給我「帳戶@ cb1edc」?

很抱歉的長期問題,這是一個簡單的問題其實只是想我給你所有的信息,我可以。謝謝。

+0

你能告訴你'Account'類嗎? –

+0

'Account'類中有'toString'方法嗎? –

+0

爲什麼它會存在,如果你還沒有把它放在地圖上呢? –

回答

2

這是正確的行爲。 account.get(accountID)返回正在從JVM內存轉儲中打印的Account對象。

爲了得到一些清晰的輸出,賬戶類需要返回有用信息的字符串一個toString方法。

當您嘗試將對象打印到控制檯時,JVM會自動搜索toString方法並使用該方法對對象進行字符串化(使其具有人性化可讀性),如果無法找到打印出對象的方法該對象的JVM內部存儲器標識看起來有點像垃圾。試試這個:

public String toString() { 
    return "This is account " + this.id; // or something like this 
} 
+0

快速回復!不知道爲什麼我沒有考慮使用toString。添加到HashMap後我嘗試做「System.out.println(account.get(toString()));」 。但現在我收到null – StackMeUp123

+0

排序它現在歡呼 – StackMeUp123