【发布时间】: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