【发布时间】:2021-06-19 17:45:00
【问题描述】:
我只是想问一下如何读取CSV文件的内容并将其放入二维数组中。
我的 CSV 文件的内容每行包含 7 列(以逗号分隔的“,”)。另一方面,行由破折号/连字符“-”分隔。但请注意,这些行仍然在同一行上(它们只是在有分隔 7 列(每行)的破折号/连字符时才被识别。
(CSV 文件中显示的内容是用户输入的,即用户为每行的列输入 7 个值。)
我的问题是,每当用户完成输入第一行的值时,我都会得到一个 java.lang.ArrayIndexOutOfBoundsException: 7 它来自我的二维数组声明的 7 列(我打算在其中插入CSV 文件)在我的 readCustomerCSV 函数中。
函数的具体行是这样的:read2DString[read2DStringIndex][g] = fromfile[g];
这是我的源代码:
public void writeCustomerCSV() { // everything in this snippet code works fine(it creates a CSV file which stores the inputs of the user)
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
StringBuilder sb = new StringBuilder();
int y;
for (int x = 0; x < itemTo2D.length; x++) {
for (y = 0; y < itemTo2D[0].length; y++) {
if (itemTo2D[x] != null) {
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
} catch (Exception ex) {
}
}
public void readCustomerCSV() { // reads the contents of the CSV file *having issues with ArrayINdexOutofBounds
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
String[][] read2DString = new String[10][7]; // 2D array where the contents of the CSV file will be inserted (can only get 10 unique values of 7 columns)
try {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null) {
fromfile = line.split(","); //separates the columns by a comma
}
} catch (Exception ex) {
}
for (int g = 0; g < fromfile.length; g++) {
read2DString[read2DStringIndex][g] = fromfile[g]; // the ArrayIndexOutofBounds is here (inserts the values of the 2D array(by row))
// System.out.print(fromfile[g] + " ");
if (fromfile[g].equals("-")) { //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
}
}
}
我的代码中是否有任何遗漏或者我的方法不够好?
【问题讨论】:
-
我可能是错的,但它看起来像代表新行的破折号,在第 7 个索引(列表中的第 8 个项目)添加到 read2DString 时会触发越界异常(g 会等于 7,这是超出范围的,因为该列表需要第 8 列)。我认为解决方案是先放置 if 语句,然后使用 continue 语句退出该迭代,然后再将其添加到数组以绕过问题。
-
基本上,您的程序将“-”视为第 8 列,然后再转到下一行。 “第 8 列”将超出范围。
-
我尝试将声明的 7 更改为 8 但仍然得到一个 ArrayIndexOutOfBounds,特别是它指出 java.lang.ArrayIndexOutOfBoundsException: 8
-
您还必须使用模运算符 (%) 在每行之后将列重置为 0
-
哦,好吧,我会使用那个模数运算符,但是我会把它放在代码的哪一部分呢??
标签: java arrays csv multidimensional-array