Gintoki
Gintoki

Reputation: 97

How do I return back specific data from a csv?

I've written code based on the exercise question but it's not returning the correct the number. It feels as if I did everything right.

 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;
}

Here is the output:

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

As you can see it's returning back a very similar number.

Upvotes: 0

Views: 57

Answers (1)

Bor Laze
Bor Laze

Reputation: 2506

You have a several mistakes in your code.

1) You need totalAmount instead of single price and volume.

2) In your if() are missed {} (volume = Double.parseDouble(dataArray[2]); is always executed)

As result, you return [last price in given day] * [last volume in file]. I think, it's a bit different than you expect.

3) So, your code should be something like this:

double totalAmount = 0.0;

...

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

...

return totalAmount;

In this case totalAmount is sum of price * volume for all records for given day.

Upvotes: 1

Related Questions