2013-05-02 79 views
0

假設我在我的程序中有以下hashmap設置..我想獲取hashmap的輸入並將它們存儲到一個對象中。當前的hashmap列表太長而無法放入主代碼,所以我試圖從一個單獨的目標文件中讀取輸入以限制主代碼的長度。你會如何推薦我去做這件事?將hashmap的鍵/值輸入到一個對象中

謝謝!

int i = input.nextInt(); 
Map<Character,Integer> map = new HashMap<Character,Integer>();       

map.put('A', i*2);       
map.put('B', i*2); 
map.put('C', i*2); 
map.put('D', i*4); 
map.put('E', i*2); 
map.put('F', i*3); 
map.put('G', i*2); 
map.put('H', i*6); 
        and so on forth down to Z and other 20 other characters... 
+0

表達式總是'i * 2'嗎?它們對於所有字母「A'..''Z」都一樣嗎? – dasblinkenlight 2013-05-02 01:08:55

+0

它們對於某些字符有所不同。我只是複製/粘貼前幾個。讓我暫時編輯它,所以別人不認爲這太 – harshm0de 2013-05-02 01:09:48

+0

我認爲我* 2應該有一個模式,所以你可以使它與循環:) – cakil 2013-05-02 01:17:51

回答

0

你的意思是這樣的:

int i=1000;//anything what you like 
Map<Character,Integer> map = new HashMap<Character,Integer>(); 
for(int x=65;x<=90;x++){ 
     char c=(char)x; 
     map.put(c, i*2); 
}  
+0

不幸的是,我* 2不完全是每個單一字符模式。它對於後面的一些字符有所不同 – harshm0de 2013-05-02 01:26:19

0

假設這些乘數沒有改變,那麼你可以做到以下幾點。

int[] multipliers = {2,2,2,4,2,3,6,...}; 
char chars[] = {'A','B',...}; /// or if they are in ascii order you dont need to specify this 
for (int j=0;j<chars.length;j++){ 
    map.put(chars[j],i * multipliers[j]); 
} 

只要確保您的兩個數組的大小相同即可。

相關問題