为什么这段代码将相同的条目从我的csv文件添加到2d数组?



我正在从一个名为订票的csv文件中读取,该文件目前有3行

1,000,Test Name,1,First
2,000,Another Name,2,First
3,001,Yet Another,3,Business

我有一个方法,旨在读取文件并将每个元素添加到2d预订数组中,然而,该方法反而将相同的记录添加到2d数组中的所有元素

输出:

Bookings: [[3, 001, Yet Another, 3, Business], [3, 001, Yet Another, 3, Business], [3, 001, Yet Another, 3, Business]

代码:

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

请让我知道我是否需要更多地解释代码或如果有任何困惑,并提前感谢您的帮助。

读取每一行,解析它,然后继续将其值添加到从0到flightlength的所有行中,每次都是这样。

相反,您需要读取每一行,解析它,然后将其添加到预订的下一行。

有效地,摆脱破坏你的for (int row = 0; row < flightsLength; row++) {(和匹配的}),并保持你自己的row索引,如:

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

最新更新