我在将 CSV 文件转换为 Java 中的二维数组时遇到了一些问题。我可能会走最长的路,但我似乎无法弄清楚我为什么会出错。每行和每列应该有 25 个元素。这是我的代码:
BufferedReader CSVFile = new BufferedReader(new FileReader(fileName));
String dataRow = CSVFile.readLine();
// Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.
while (dataRow != null) {
dataRow.split(",");
list.add(dataRow);
dataRow = CSVFile.readLine();
// Read next line of data.
}
// Close the file once all data has been read.
CSVFile.close();
String[] tokens = null;
Object[] test = list.toArray();
String[] stringArray = Arrays.copyOf(test, test.length, String[].class); //copies the object array into a String array
//splits the elements of the array up and stores them into token array
for (int a = 0; a < test.length; a++) {
String temp = stringArray[a];
tokens = temp.split(",");
}
//converts these String tokens into ints
int intarray[] = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
intarray[i] = Integer.parseInt(tokens[i]);
}
//attempts to create a 2d array out of a single dimension array
int array2d[][] = new int[10][3];
for (int i = 0; i < 25; i++) {
for (int j = 0; j < 25; j++) {
array2d[i][j] = intarray[(j * 25) + i];
}
}
我相信错误是当 ArrayList 被复制到第一个 String 数组时,但我不能确定。该文件有 25 列和 25 行。我不断得到的错误是数组在索引 25 处超出范围。任何输入将不胜感激。谢谢!