【问题标题】:How do I return back specific data from a csv?如何从 csv 返回特定数据?
【发布时间】:2017-05-07 12:05:19
【问题描述】:

我已经根据练习题编写了代码,但它没有返回正确的数字。感觉好像我做的一切都是正确的。

 static double Q3(String stockFilename, String date) {

    // Given a filename with stock data in the format "date,price,volume" and a date, return the total value of all
    // shares of the stock that were traded that day. The total value is price times (multiplication) volume.

    String line = "";
    String dataArray[];
    double price = 0.0;
    double volume = 0.0;
    try {
        BufferedReader br = new BufferedReader(new FileReader(stockFilename));

        while ((line = br.readLine()) != null) {
            dataArray = line.split(",");

            if(dataArray[0].equals(date)) //Finds the date of that day
                price = Double.parseDouble(dataArray[1]); //Grabs price 
                volume = Double.parseDouble(dataArray[2]); //Grabs volume
        }

        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return price*volume;
}

这是输出:

Incorrect on input: [data/FB_2016.csv, 2016-02-12]
Expected output : 3.6903954403536E9
Your output     : 3.8674439998248E9

如您所见,它返回的数字非常相似。

【问题讨论】:

  • 提示:我们不知道文件包含什么。但是您似乎假设该文件在给定日期只有一行。你忽略了除了最后一个找到的所有东西,所以......
  • 解决问题的第一步是隔离问题,这意味着是时候进行一些认真的调试了,或者使用允许您单步调试代码并分析变量作为程序进度,或者使用记录器,或者使用“穷人的调试器”——许多 println 语句在程序进行时暴露变量状态。
  • 你也应该停止使用 C/Pascal 在方法顶部声明所有变量的习惯。仅在需要时在尽可能窄的范围内声明它们。

标签: java file csv read-write


【解决方案1】:

您的代码中有几个错误。

1) 您需要 totalAmount 而不是单一的价格和数量。

2) 在你的 if() 中错过了 {}(volume = Double.parseDouble(dataArray[2]); 总是被执行)

因此,您返回 [给定日期的最后价格] * [文件中的最后成交量]。我想,这和你想象的有点不同。

3) 所以,你的代码应该是这样的:

double totalAmount = 0.0;

...

if(dataArray[0].equals(date)) {
  totalAmount += Double.parseDouble(dataArray[1]) * Double.parseDouble(dataArray[2]);
}

...

return totalAmount;

在这种情况下,totalAmount 是给定日期所有记录的价格 * 交易量之和。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2011-02-28
    • 2017-03-16
    • 2022-08-23
    • 2014-11-22
    • 1970-01-01
    相关资源
    最近更新 更多