Java 使用csv文件填充二维数组时,我的数组索引超出范围
我试图使用csv文件填充2D数组,但我一直收到一个错误消息:ArrayIndexOutOfBoundsException:17。问题似乎出在“for”上,但我真的很难理解为什么。感谢您的帮助,并提前表示感谢Java 使用csv文件填充二维数组时,我的数组索引超出范围,java,arrays,csv,2d,Java,Arrays,Csv,2d,我试图使用csv文件填充2D数组,但我一直收到一个错误消息:ArrayIndexOutOfBoundsException:17。问题似乎出在“for”上,但我真的很难理解为什么。感谢您的帮助,并提前表示感谢 import java.io.*; import java.util.Arrays; import java.util.Scanner; public class CSVRead { public String[][] junior = new String[17][1]; p
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class CSVRead
{
public String[][] junior = new String[17][1];
public CSVRead() throws IOException {
{
Scanner scanner = null;
int Rowc2=0;
String InputLine2 = "";
String xfilelocation2;
xfilelocation2 = ("//Users//Pdubru//Downloads//arrays.csv");
scanner = new Scanner (new BufferedReader (new FileReader (xfilelocation2)));
while (scanner.hasNextLine()){
InputLine2 = scanner.nextLine();
String[] InArray = InputLine2.split (",");
for (int x=0; x< InArray.length; x++){
junior [Rowc2][0] = InArray[x];
}
Rowc2++;
}
} //main()
System.out.println(junior [1][0]);
这是因为您说过字符串数组的限制为17-
public String[][] junior = new String[17][1];
但最终你的代码
while (scanner.hasNextLine()){
InputLine2 = scanner.nextLine();
String[] InArray = InputLine2.split (",");
for (int x=0; x< InArray.length; x++){
junior [Rowc2][0] = InArray[x]; // even this isn't useful (why explained further below)
}
Rowc2++; // this causes the Exception
}
while(scanner.hasNextLine()){
InputLine2=scanner.nextLine();
字符串[]InArray=InputLine2.split(“,”);
对于(int x=0;x
当您以以下模式存储值时-
junior[0][0]、junior[0][0]、junior[0][0]
for、男、女
junior[1][0],junior[1][0],junior[1][0]
for,24.89,28.46
。。。等等
junior[16][0]、junior[16][0]、junior[16][0]
for,2:20.00,2:35.75
RowC2
当计算值超过16时,将抛出异常。这就是您案例中的下一个输入所发生的情况。看起来您在文件中的每一行上都进行了迭代。然后在用逗号分隔的字段上迭代,并将每个值存储在数组的第二个参数中,然后立即用下一个值覆盖它(不确定为什么要这样做,但我们将继续)
如果在文件的最后一行之后有新行,您将尝试插入索引为17的行,这是不可能的,因为您只有17行,而第一个索引为0
让我们走完最后一行的步骤
InputLine2将设置为空白字符串InputLine2=“”
下一行将计算为String[]InArray=newstring[]{”“}代码>
最后,在for循环中,您将设置junior[17][0]=”
李>
这将看到上面的异常
您可能应该使用列表,而不是数组,这样文件的长度就无关紧要了
为什么不这样做:
Scanner scanner = ....
Iterable<String> iterable = () -> scanner; // convert to iterable
Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false);
String[][] data = stream.filter(s -> s != null && s.contains(","))
.map(s -> new String[] { s.substring(s.lastIndexOf(",")+1) })
.toArray();
扫描仪=。。。。
Iterable Iterable=()->扫描仪;//转换为可编辑
Stream=StreamSupport.Stream(iterable.spliterator(),false);
字符串[][]数据=流.过滤器(s->s!=null&&s.contains(“,”)
.map(s->新字符串[]{s.substring(s.lastIndexOf(“,”)+1)})
.toArray();
乍一看,您似乎只在第一列中填写矩阵,并将每行的每个值置于前一个值之下。假设您有18行,每行上有2个值,这将导致第一列中有36个值。这将导致一种出界的感觉。非常感谢!真的很感激
Scanner scanner = ....
Iterable<String> iterable = () -> scanner; // convert to iterable
Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false);
String[][] data = stream.filter(s -> s != null && s.contains(","))
.map(s -> new String[] { s.substring(s.lastIndexOf(",")+1) })
.toArray();