Skip to content
Advertisement

Summing up times using Duration

For my project, I have to read in data that is given to us in a CSV file and write it out in a certain format. I have it almost done but the problem I am having is that my program is not completely reading through the times that are given. From here my program is just reading all the times that I am given.

I’ve tried to convert String time to an Integer but it gives me an InputMismatchException.

JavaScript

This should return

[Sesame Street | Best of Elmo | 0:28:11]

but it returns

[Best of Elmo | Sesame Street | ,2:29,1:30,2:09,1:46,1:55,2:02,1:42,2:40,1:56,1:30,2:03,1:14,2:28,2:47]

Advertisement

Answer

You may consider finding and using a third-party library for reading your CSV file. There are some, also some that you can use for free.

I assume that a line in your CSV file looks like this:

JavaScript

That is, no quotes in the line and no commas within the name or album title. In this case it should be manageable to read and parse the file using Scanner the way you are trying. For scanning the times use an inner loop, Scanner.hasNext() and Scanner.next() (not Scanner.nextLine()). Parse each time from Scanner.next() into a Duration. It’s not completely trivial, but there are already answers explaining how to do that. I insert a link at the bottom. Use Duration.plus(Duration) for summing up the durations. Finally you need to format the total duration back into a string for output. I include another link for that.

Links

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement