2017-03-25 109 views
-1
/** 
* 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文件的一列到日期參數。我該如何做到這一點,以便代碼將查找一條單獨的行,然後將該行的日期[1]與該日期參數進行比較並返回該行的返回值[2]?如何比較兩個.csv文件?

+0

之間的一個空間,我們能得到更多的單詞解釋? – surajsn

回答

0

我認爲你的代碼接近於(功能)正確。您所犯的錯誤是Java數組從零開始索引,而不是從一個索引。所以Ans[1]實際上是給你數組的第二個元素......不是第一個元素。

解決方案:顯而易見...假設你明白我上面寫的東西!

一旦你已經修復了這一錯誤(S),你應該修復的作風問題:

  • 始終以小寫字母開頭的變量名。
  • 使用4個空格作爲縮進級別if
  • 一個空間。
  • ){