Java 从文件读入二维数组
我必须从如下文件中读取数据:Java 从文件读入二维数组,java,arrays,Java,Arrays,我必须从如下文件中读取数据: 4 192 48 206 37 56 123 35 321 21 41 251 42 442 32 33 第一个数字是候选(列)的总数,我需要存储该值以供其他使用。然后我需要将其余的数据读入2D数组。我用现在的代码更新了我的代码,但它仍然不起作用。我一直在犯错误 java.util.NoSuchElementException:未找到任何行 public static int readData(int[][] table, Scanner in)throws I
4
192 48 206 37 56
123 35 321 21 41
251 42 442 32 33
第一个数字是候选(列)的总数,我需要存储该值以供其他使用。然后我需要将其余的数据读入2D数组。我用现在的代码更新了我的代码,但它仍然不起作用。我一直在犯错误
java.util.NoSuchElementException:未找到任何行
public static int readData(int[][] table, Scanner in)throws IOException
{
System.out.println("Please enter the file name: ");
String location = in.next();
Scanner fin = new Scanner(new FileReader(location));
int candidates = fin.nextInt();
fin.nextLine();
for (int row = 0; row < 5; row++) {
for (int column = 0; column < candidates; column++) {
String line = fin.nextLine();
fin.nextLine();
String[] tokens = line.split(" ");
String token = tokens[column];
table[row][column] = Integer.parseInt(token);
}
}
fin.close();
return candidates;
}
}
public static int readData(int[]table,Scanner in)引发IOException
{
System.out.println(“请输入文件名:”);
字符串位置=in.next();
扫描仪fin=新扫描仪(新文件读取器(位置));
int候选者=fin.nextInt();
fin.nextLine();
对于(int行=0;行<5;行++){
for(int column=0;column
据我所知,您的主要任务是从文件中提取整数值,并将其放入2D数组中
我建议您参考Oracle网站上的Scanner API参考:
您可以在那里发现,有一些更适合您的任务的方法:
candidates
是列数,则应将其视为整数,而不是字符串:
int candidates = fin.nextInt();
通过使用上述扫描方法,不再需要从文件中获取字符串
值,因此行
和数字
变量可以从源代码中完全删除
使用hasNextLine()
方法,您可以确保该文件将一直读取到其结束:
int row = 0;
while(fin.hasNextLine()) { //while file has more lines
for(int col = 0; col < candidates; j++) { //for 'candidates' number of columns
table[row][col] = fin.nextInt(); //read next integer value and put into table
}
row++; //increment row number
}
int行=0;
while(fin.hasNextLine()){//while文件有更多行
对于(int col=0;col
请记住,Java数组不是动态可伸缩的
您的2D数组-表
应该使用要放入其中的数据的精确大小进行初始化
在您当前的示例中,直到文件末尾您才知道输入行的数量,因此正确初始化数组可能需要额外的操作。定义“完全不工作”。发生了什么事?华夫饼干从屏幕上出来了吗?首先,您忽略了
候选对象
。其次,您只需阅读第一行:fin.nextLine()代码>应在每次迭代中。获取错误java.lang.NumberFormatException:对于输入字符串:“输入文件名后,我如何忽略候选项?”?我不明白。你在循环中硬编码5,而不是解析候选项
,这是预期要读取的行数。那么,你没有在每次迭代中阅读。啊,是的,我明白了,谢谢。帮助我,一个吨级的家伙现在工作得很好,谢谢你的帮助,很高兴听到:)干杯!