/**
* 5 points
*
* Return the price of the stock at the given date as a double. Each line
* of the file contains 3 comma separated
* values "date,price,volume" in the format "2016-03-23,106.129997,25703500"
* where the data is YYYY-MM-DD, the price
* is given in USD and the volume is the number of shares traded throughout
* the day.
*
* Note: You don't have to interpret dates for this assignment and you can use
* the Sting's .equals method to
* compare dates whenever date comparisons are needed.
*
* @param stockFileName The filename containing the prices for a stock for each
* day in 2016
* @param date The date to lookup given in YYYY-MM-DD format
* @return The price of the stock represented in stockFileName on the given date
*/
public static double getPrice(String stockFileName, String date) {
try {
BufferedReader br = new BufferedReader(new FileReader(stockFileName));
String line = "";
String unparsedFile = "";
Double Price;
while ((line = br.readLine()) != null) {
String[] Ans = unparsedFile.split(",");
for (String item : Ans){
if(Ans[1].equals(date)){
double aDouble = Double.parseDouble(Ans[2]);
return aDouble;
}
}
}
br.close();
} catch (IOException ex) {
System.out.println("Error");
}
return Ans;
}
我现在的代码将假设只将.csv文件的一列与date参数进行比较。如何使代码查找单个行然后将该行的[1]与date参数进行比较并返回该行的[2]?
答案 0 :(得分:0)
我认为您的代码接近于(功能上)正确。您犯的错误是Java数组从零开始索引,而不是从一个索引。所以Ans[1]
实际上是给你数组的第二个元素......而不是第一个元素。
解决方案:显而易见......假设你明白我刚才写的内容!
修复错误后,您应该修复样式问题:
if
之后的一个空格。)
和{