我有一个从文本文件中获取数据的程序。该文件的格式如
Date/Time Tip From (Name)
Message(If one was left)
(Tipped Amount) (Total Tips Recieved)
我已经能够让我的代码将其分离出来并将其放入 map 中,这样它就可以将每个名称的所有提示相加并以降序方式输出。
例如
INPUT ----------------------------------
Dec. 14, 2013, 2:31 a.m. Tip from rs
25 24986
Dec. 14, 2013, 2:27 a.m. Tip from ro
100 24961
Dec. 14, 2013, 2:27 a.m. Tip from rs
15 24861
Dec. 14, 2013, 2:25 a.m. Tip from da
3 24846
OUTPUT-----------------------------------
ro=100
rs=40
da=3
我现在遇到了一个问题。我发现我正在丢失数据,但不明白为什么。该文本文件中有 1,000 多个条目,因此大约有 2,000 行文本。其中一名小费者 X,经手工计算,小费为 1990。运行时,程序仅计算出 1690,比实际小费少了 300。我无法尝试调试它以找出数据可能被删除或跳过的位置。
这是我与正在执行的计算器相关的代码的摘录
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("Tip from")) { // Finds the line that contains
// the tippers name
final String tipperName = line.substring(line
.indexOf("from ") + 5);
currentTipper = tipperName;
} else if (line.substring(0, 1).matches("\\d")) { // finds the
// line that
// contains
// the
// tipped
// amount
final Integer tipValue = Integer.parseInt(line.substring(0,
line.indexOf("\t")));
// here we store the tip in the map. If we have a record
// we
// sum, else
// we store as is
tipsByName
.put(currentTipper,
(tipsByName.get(currentTipper) == null ? 0
: tipsByName.get(currentTipper))
+ tipValue);
} else { // if line doesnt contain a name or a tip, skips to
// next line
bufferedReader.readLine();
}
}
如果完整的代码会更有帮助,请告诉我,我将编辑该帖子。
谢谢!
最佳答案
我认为您有重复的条目,这就是您“丢失数据”的原因。在将条目插入 map 之前,请尝试查看 key 是否已经存在。
关于java - 丢失数据,Map 包含字符串和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20608881/