I am reading from a csv file called bookings which has 3 rows currently
1,000,Test Name,1,First
2,000,Another Name,2,First
3,001,Yet Another,3,Business
I have a method which is meant to read through the file and add each element into a 2d array of bookings, however, the method instead adds the same record to all elements in the 2d array
Output:
Bookings: [[3, 001, Yet Another, 3, Business], [3, 001, Yet Another, 3, Business], [3, 001, Yet Another, 3, Business]
Code:
public class Booker {
int flightsLength;
int nextFlight;
// 2D Array representing bookings
String[][] bookings = new String[1000][5];
// Read bookings from csvr
//file path
String path ="bookings.csv";
//current line being read
String line;
public void readBookings() {
try {
//new buffered reader object named br
BufferedReader br;
System.out.println("RUNNING:");
//initialise the buffered reader with the file as a parameter
br = new BufferedReader(new FileReader(path));
// Store length of flights csv
flightsLength = getFlightsCount();
//while next line is available, loop
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (int row = 0; row < flightsLength; row ) {
for (int cell = 0; cell <= 4; cell ) {
bookings[row][cell] = values[cell];
}
}
}
System.out.println("Bookings: " Arrays.deepToString(bookings));
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
Please let me know if I should explain the code more or if there is any confusion, and thank you in advance for the help.
CodePudding user response:
You read each line, parse it, and then proceed to add its values to ALL the rows from 0 to flightsLength, every time.
Instead you need to read each line, parse it, and then add it to the next row in your bookings.
Effectively, get rid of the for (int row = 0; row < flightsLength; row ) {
(and the matching }
) that ruin things for you, and maintain your own row
index, something like:
int row = 0;
//while next line is available, loop
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (int cell = 0; cell <= 4; cell ) {
bookings[row][cell] = values[cell];
}
row ;
}