Java 如何从csv返回特定数据?
我已经根据练习题编写了代码,但没有返回正确的数字。感觉好像我做的每件事都是对的Java 如何从csv返回特定数据?,java,file,csv,read-write,Java,File,Csv,Read Write,我已经根据练习题编写了代码,但没有返回正确的数字。感觉好像我做的每件事都是对的 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 t
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
正如您所看到的,它返回了一个非常相似的数字。您的代码中有几个错误 1) 你需要的是总量,而不是单一的价格和数量 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是给定日期所有记录的价格*数量之和。提示:我们不知道该文件包含什么。但您似乎认为该文件在给定日期只有一行。除了最后一个,你忽略了所有发现的问题,所以…解决问题的第一步是隔离你的问题,这意味着是时候进行一些认真的调试了,或者使用一个调试器,允许你在程序进行时逐步通过代码和分析变量,或者使用一个记录器,或者使用一个“穷人的调试器”--许多println语句会随着程序的进行而暴露变量状态。您还应该停止使用C/Pascal在方法顶部声明所有变量的习惯。仅在需要时在尽可能狭窄的范围内声明它们。