我有以下内容:
氢化物锂: Li 1H1#评论.
我希望得到以下结果:
{氢化锂:{‘Li’:1,‘H’:1},.}
我是这样做的:
public static HashMap<String,HashMap<String,Integer>> readFormulas(String content){
HashMap<String,Integer> dictionnaire1 = new HashMap<String,Integer>();
HashMap<String,HashMap<String,Integer>> dictionnaire2 = new HashMap<String,HashMap<String,Integer>>();
ArrayList <String> al = new ArrayList<String>();
al.add(Arrays.toString(content.split(":")));// on met chaque ligne dans un tableau
String str[] = content.split("\n");
for(int i = 0 ; i < str.length;i++){//pour chaque ligne
String str2 [] = str[i].split(":");// séparer les noms des molécules des noms scientiques et des commentaires ["Helium","he 1 #fzefzezfezfz"
String NomMolecule = str2[0];
String diese [] = str2[1].split("#");
String description [] = diese[0].split(" ");
int nb = Integer.parseInt(description[2]);
dictionnaire1.put(description[1], nb);
}
dictionnaire2.put(NomMolecule,dictionnaire1);
}
return(dictionnaire2);
}但是结果很糟糕,我不明白为什么?:条目:
HashMap<String,HashMap<String,Integer>> formulas = readFormulas("helium : he 3 #fsdfsfsdfsf" + "\n" + "lithium hydride : Li 1 H 1 #fdvdfdfvd");结果:
{氢化锂={he=3,Li=1},氦={he=3,Li=1}
发布于 2015-09-20 14:54:27
每个分子都需要一个HashMap:
for(int i = 0 ; i < str.length;i++){//pour chaque ligne
String str2 [] = str[i].split(":");
String NomMolecule = str2[0];
String diese [] = str2[1].split("#");
String description [] = diese[0].trim().split(" ");
HashMap<String,Integer> dictionnaire1 = new HashMap<>();
for( int j = 0; j < description.length; j += 2 ){
int nb = Integer.parseInt(description[j+1]);
dictionnaire1.put(description[j], nb);
}
dictionnaire2.put(NomMolecule,dictionnaire1);
}你也错过了一个环,在一个分子的成分(例如,Li _1H_ 1)上,这是我添加的。
发布于 2015-09-20 14:58:19
HashMap<String,Integer> dictionnaire1 = new HashMap<String,Integer>();由于这个HashMap在每个循环迭代中都被重用,所以以前的(陈旧的)映射元素会产生错误的输出。
说明:
在第一次迭代中dictionnaire1:{he:3}
在第二次迭代中,相同的映射将与以前的字段数据一起重用。
找到的数据项- {Li: 1} & {he:3}
就是这样,你得到了结果。{Li: 1,he:3}
要获得所需的结果:
First您需要在每次迭代中清除dictionnaire1的所有先前条目。
第二个,您需要调整逻辑,从description数组中检索多个元素-
for(int j=1;j<description.length-1;j+=2){
int nb = Integer.parseInt(description[j+1]);
dictionnaire1.put(description[j], nb);
}https://stackoverflow.com/questions/32680630
复制相似问题