有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将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...

共 (2) 个答案

  1. # 1 楼答案

    你的意思是:

    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);
    }    
    
  2. # 2 楼答案

    假设这些乘数不必改变,那么你可以做以下事情

    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]);
    }
    

    只需确保两个阵列的大小相同即可