java - 丢失数据,Map 包含字符串和整数

标签 java

我有一个从文本文件中获取数据的程序。该文件的格式如

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/

相关文章:

java - 带有 Glassfish 的 Geotools : Failed to connect to the EPSG database

java - 如何使用 iText 在 jFreeChart 中写入西里尔字符

java - 在 Oracle 12C jdbc 驱动程序中获取自动递增 key 时出现 NPE

java - 两个 socket 仅用于一个连接

java - 在 TeeChart 中绘制 Graphics3D

java - 让 FillLayout 表现正确

java - Java 垃圾收集器在这里是如何工作的?

java - 在 Java 应用程序中使用 Minishift 观察者

java - 二叉搜索树,添加相同元素异常(exception)。

java - 如何格式化数字以仅在非 0 时包含 "+/-"?