这是我的代码
for (String k : word1.keySet()) {
System.out.println(k + "\t" + word1.get(k));
//int c+=word1.get(k);
}
System.out.println(word1.size());
此代码的输出是
Photos 0.6337632198238539
software 0.20454545454545456
service 0.09090909090909091
applications -0.20391337869173334
注释行显示错误。帮帮我!!!
答案 0 :(得分:1)
您将地图声明为Map<String, String>
,这个问题确实值得一提,而不只是在评论中提及。
import java.util.HashMap;
import java.util.Map;
public class Scratch {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("Photos", "0.6337632198238539");
map.put("software", "0.20454545454545456");
map.put("service", "0.09090909090909091");
map.put("applications", "-0.20391337869173334");
double c = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
System.out.println(k + "\t" + v);
c += Double.parseDouble(v);
}
System.out.println("===");
System.out.println("Total: " + c);
}
}
输出:
Photos 0.6337632198238539
software 0.20454545454545456
service 0.09090909090909091
applications -0.20391337869173334
===
Total: 0.7253043865866661
这就是我讨厌使用\t
的原因。标签很痛苦。
答案 1 :(得分:0)
一个错误是初始化循环内的计数。它应该在外面。如果地图保持双值,它也应该是双倍的。
double c = 0.0;
for (String k : word1.keySet()) {
System.out.println(k + "\t" + word1.get(k));
if (words1.get(k) != null)
c += word1.get(k);
}
现在,如果您收到异常,您的地图可能包含空值。如果是这种情况,请在上面的代码中添加一个空检查。
答案 2 :(得分:0)
首先,您需要声明变量以在循环之前保存总和。其次,数字显然不是整数,因此您需要相应地声明总和:
double total = 0.0;
for (String k : word1.keySet()) {
System.out.println(k + "\t" + word1.get(k));
total += word1.get(k);
}
(假设值是双倍的,例如,如果map被声明为
Map<String,Double> word1
更新:当您的地图声明为Map<String, String>
时,您需要将值转换为double:
double total = 0.0;
for (String k : word1.keySet()) {
System.out.println(k + "\t" + word1.get(k));
try {
total += Double.valueOf(word1.get(k));
}
catch(Exception e) {
// count the value as 0 if cannot convert to a double
}
}
答案 3 :(得分:0)
HashMap<String, Double> map = ...
double sum = 0.0;
for (Entry<String, Double> entry : map.entrySet()) {
System.out.println(entry.getKey() + "\t" + entry.getValue());
sum += entry.getValue();
}