显然我已经找到了另一个关于此问题的帖子,但它并没有以任何方式帮助我。
我的问题:输出
如下所示,问题出在if语句中。那么if语句应该怎么做呢?
如果它不包含,那么只需将licenseplateList.get(i)作为键,并添加值kmperlineList.get(i)
对于整个代码检查: https://pastebin.com/jaSTm1DR
if (before) {
// does our map already contain this license?
if (nachtMap.containsKey(licenseplateList.get(i))) {
kmperlineList.get(i).replaceAll(",", ".");
// then remove that one, add new one but have the sum of the values
// is this extra ) after ".get(i)" correct?
Double sum = nachtMap.remove(licenseplateList.get(i)) + Double.parseDouble(kmperlineList.get(i));
nachtMap.put(licenseplateList.get(i), sum);
}
// if it doesnt contain the license yet, just put it in there
else {
kmperlineList.get(i).replaceAll(",", ".");
nachtMap.put(licenseplateList.get(i), Double.parseDouble(kmperlineList.get(i)));
}
}
// if its not before 06:00
else {
// als de tijd na 17:30 is
if (after) {
if (nachtMap.containsKey(licenseplateList.get(i))) {
Double sum = nachtMap.remove(licenseplateList.get(i)) + Double.parseDouble(kmperlineList.get(i));
nachtMap.put(licenseplateList.get(i), sum);
} else {
kmperlineList.get(i).replaceAll(",", ".");
nachtMap.put(licenseplateList.get(i), Double.parseDouble(kmperlineList.get(i)));
}
}
// otherwise it's always day
else {
// again: does the map already contain this license plate?
if (dagMap.containsKey(licenseplateList.get(i))) {
System.out.println("works");// debug
kmperlineList.get(i).replaceAll(",", ".");
// then get the sum of the values, but only 1 time the key
Double sum = dagMap.remove(licenseplateList.get(i)) + Double.parseDouble(kmperlineList.get(i));
dagMap.put(licenseplateList.get(i), sum);
}
// if the map does not contain the license plate
else {
kmperlineList.get(i).replaceAll(",", ".");
dagMap.put(licenseplateList.get(i), Double.parseDouble(kmperlineList.get(i)));
}
}
}
答案 0 :(得分:0)
您的代码过于复杂且冗余。
但首先,您的文件似乎使用的是非美国数字格式(1000,00
,而不是1000.00
),因此您应该使用NumberFormat
并使用正确的Locale
进行解析数字,而不是解析Java语法数字的Double.parseDouble
。
假设Java 8(因为所有早期版本现已停止使用),您的代码可以简化为:
double kmperline = NumberFormat.getNumberInstance(Locale.GERMANY)
.parse(kmperlineList.get(i)).doubleValue();
Map<String, Double> mapToUpdate = (before || after ? nachtMap : dagMap);
mapToUpdate.merge(licenseplateList.get(i), kmperline, Double::sum);