Reputation: 35
so I'm new to using BufferedReader to read from a file, as well as using arrayLists in Java. I was wondering why my code doesn't store the correct data inside each DVD object inside of the arrayList. The way I originally thought this works is that it starts at the top of the text file, reads the line, and then stores that information inside of a variable. After it finishes reading a double value it then creates a DVD object based on the information it previously found. Then the file will continue to read and store the remaining data inside of the arrayList. However, I receive this at the beginning of the arrayList...
DVD Title: Drama, DVD Category: 130 minutes, DVD Running Time: 2002, DVD Year: 50, DVD Price: 52.0
There are multiple things wrong here. First, the title should be "Mystic River" but it skipped that line and stored the category "Drama" instead. Additionally, the year and price information are blatantly wrong for the remainder of the file reading process. After the first entry, the title, category and running time data are appropriately stored as shown below.
DVD Title: Everest, DVD Category: Documentary, DVD Running Time: 78 minutes, DVD Year: 50, DVD Price: 48.0
What is causing the data to be stored incorrectly?
ArrayList<DVD> DVDArrayList = new ArrayList<DVD>();
try
{
BufferedReader kbd = new BufferedReader(new FileReader("DVDCollection.txt")); // Open the DVDCollection file.
String line;
while ((line = kbd.readLine()) != null) // Read the contents.
{
String dvdTitle = kbd.readLine();
String dvdCategory = kbd.readLine();
String dvdRunningTime = kbd.readLine();
int dvdYear = kbd.read();
double dvdPrice = (double) kbd.read();
DVDArrayList.add(new DVD (dvdTitle, dvdCategory, dvdRunningTime, dvdYear, dvdPrice));
}
kbd.close(); // Close file after reading
}
catch (Exception e)
{
System.out.println("Error reading file.");
}
This is the data file
Mystic River
Drama
130 minutes
2002
24.99
Everest
Documentary
78 minutes
2012
7.99
Life is Beautiful
Drama
125 minutes
1999
15.99
Village in China
Documentary
60 minutes
2006
11.99
Marley and Me
Comic
150 minutes
2008
17.99
Halloween Night
Mystery
80 minutes
2010
9.99
Upvotes: 0
Views: 126
Reputation: 212
3 Problems:
line
variable but not using it due to which dvdTitle
data is lostread()
for year will read single characterread()
for price will read single characterLogic:
String line;
while ((line = kbd.readLine()) != null) {
String dvdTitle = line;
String dvdCategory = kbd.readLine();
String dvdRunningTime = kbd.readLine();
int dvdYear = Integer.parseInt(kbd.readLine());
double dvdPrice = Double.parseDouble(kbd.readLine());
DVDArrayList.add(new DVD(dvdTitle, dvdCategory, dvdRunningTime, dvdYear, dvdPrice));
}
DVDArrayList.stream().forEach(System.out::println);
Upvotes: 2