gpt4 book ai didi

java - hashMap的HashMap

转载 作者:行者123 更新时间:2023-11-30 03:15:44 25 4
gpt4 key购买 nike

我有这个内容:

lithium hydride : Li 1 H 1 #comment...

我想要以下结果:

{lithium hydride’ : {’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");

结果:

{lithium hydride ={he=3, Li=1}, helium ={he=3, Li=1}}

最佳答案

每个分子都需要一个 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 1 H 1)的循环,这是我添加的。

关于java - hashMap的HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com