2017-04-18 45 views
0

爲了幫助自己學習java,我使用JForm GUI創建了一個二十一點程序,其中包含可以創建的帳戶並保持用於在每個遊戲上投注的運行餘額。我有一個BlackJackApp.JForm類,它是主類。帳戶存儲在.txt文件中,並使用包含readFile和writeFile方法的Account類讀取。我創建了一個樣本TXT文件,名爲Accounts.txt,使用這些值:我的散列表只是將空值

李四>>百萬

傑克·布萊克>> 1

鮑勃·多爾>> 987654321

(有在實際的txt文件中行之間沒有空格)

我有一個讀取文本文件並將這些值附加到HashMap的方法。這是我對該方法的代碼。

public void readFile() 
{ 
    accountsMap.clear(); 
    BufferedReader br; 

    try 
    {  
    br = new BufferedReader(new FileReader("Accounts.txt")); 
    String nextLine = br.readLine(); 

     while(nextLine != null) 
     { 
      String lineString[] = nextLine.split(">>"); 
      Integer accountBalance = Integer.parseInt(lineString[1]); 
      System.out.println(lineString[0] + " " + lineString[1] + " " + 
      accountBalance); 
      accountsMap.put(lineString[0], accountBalance); 
      nextLine = br.readLine(); 
     } 
     br.close(); 
    } 
    catch(IOException frex) 
    {System.out.println("An error has occurred while reading the file");} 
} 

這是相關的代碼我對JForm類,與包括以供參考

public class BlackjackApp extends javax.swing.JFrame { 

Account a = new Account(); 
String account; 
Integer accountBalance; 
HashMap accountsMap = a.getAccountsMap(); 


public void fillAccountNameBox() 
{ 

    for (int i = 0; i < accountsMap.size(); i++) 
    { 
     accountNameBox.addItem((String) accountsMap.get(i)); 
    } 


} 

public BlackjackApp() { 
    initComponents(); 
    a.readFile(); 
    fillAccountNameBox(); //fills comboBox component w/ list of hashMap keys 
    System.out.println(accountsMap.keySet()); 
    for(int i = 0; i < accountsMap.size(); i++) 
     System.out.println(accountsMap.get(i)); 

} 

的代碼的System.out.println對於調試僅在頂部。這是輸出:

John Doe 1000000 1000000 
Jack Black 1 1 
Bob Dole 987654321 987654321 
[Bob Dole, John Doe, Jack Black] 
null 
null 
null 

我的問題是這樣的:爲什麼我的散列表放入正確的鍵,但留下它們的值爲空? lineString數組正確填充,Integer accountBalance也是如此,但實際上將鍵/值對放入哈希映射中時,它只會將鍵放入,並且即使accountBalance不爲null,也會將其值留空。爲什麼是這樣?我已經嘗試過尋找許多關於這個問題的建議,但是他們的建議都不適合我。必須有一些我可以忽略的東西,但作爲初學者,我很難認識到問題所在。

回答

2

問題依賴於您打印信息的方式。 Map.get方法期望您傳遞一個參數和一個您想要的值的鍵。在for循環中,您要求附加到鍵0,1和2的值 - 因此爲空值。 你的代碼改成這樣:

for(String key : accountsMap.keySet()) 
    System.out.println(accountsMap.get(key)); 

正如你所看到的,我也改變了使用的for-each for循環結構。

希望這可以幫助你。

+0

我終於明白我出錯了,非常感謝你!我還在fillAccountBox()方法中更改了我的代碼,以便該框將使用散列映射中的鍵的ArrayList填充。 – Matthew

+0

不客氣,我很高興能夠幫到你。順便提一下,還有兩件事: 1)Map接口也有一個[values](http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#values - )方法,您可以使用它來獲取值的集合,如果您不需要這些鍵,例如fillAccountNameBox方法。 2)在泛型上添加類型是一種很好的做法。 * HashMap *而不是在沒有它們的情況下保留_HashMap_ –

2

你的地圖包含你想要它包含的內容。問題在於你如何訪問它。

正如你所指出的,在你的映射中的鍵如下:

[Bob Dole, John Doe, Jack Black] 

在最終for循環,你正在尋找訪問映射到按鍵012值。由於這些密鑰不存在於您的地圖中,因此您將獲得null