Java

时间:2016-07-25 14:47:21

标签: java

我试图解决Java中的计算问题。

假设我的数据如下:

466,2.0762
468,2.0799
470,2.083
472,2.0863
474,2.09
476,2.0939
478,2.098

它是有序对的列表,形式为[int],[double]。我文件中的每一行都包含一对。该文件可以包含七到七千行,所有这些行都被格式化为纯文本。

必须从上面一行的[int]中减去每个[int],并将结果写入另一个文件。必须对每[双]进行相同的计算。例如,在上面报告的数据中,计算应该是:

478-476 -> result to file
476-474 -> result to file
(...)
2.098-2.0939 -> result to file
2.0939-2.09 -> result to file

等等。

请原谅,如果这个问题对你们绝大多数人来说都是微不足道的,但经过几周的努力解决之后,我无处可去。我在这块板上找到甚至远程相似的东西也遇到了麻烦! 任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

  1. 阅读文件
  2. 构建结果
  3. 写入文件
  4. 对于1. task,这里已经有好几个好的答案,例如试试这个:Reading a plain text file in Java

    您知道,我们可以阅读文件line per line。您可以使用包含文件行的List<String>来构建2. task

    List<String>。让我们遍历所有行并构建结果,再次为List<String> inputLines = ... List<String> outputLines = new LinkedList<String>(); int lastInt = 0; int lastDouble = 0; boolean firstValue = true; for (String line : inputLines) { // Split by ",", then values[0] is the integer and values[1] the double String[] values = line.split(","); int currentInt = Integer.parseInt(values[0]); double currentDouble = Double.parseDouble(values[1]); if (firstValue) { // Nothing to compare to on the first run firstValue = false; } else { // Compare to last values and build the result int diffInt = lastInt - currentInt; double diffDouble = lastDouble - currentDouble; String outputLine = diffInt + "," + diffDouble; outputLines.add(outputLine); } // Current values become last values lastInt = currentInt; lastDouble = currentDouble; }

    3. task

    对于SOoutputLines上又有一个很好的解决方案。您需要遍历dotnet AssName.dll并将每行保存在文件中:How to create a file and write to a file in Java?