【问题标题】:reading from file into 2D array [closed]从文件读入二维数组[关闭]
【发布时间】:2016-03-02 20:55:36
【问题描述】:

我必须从这样的文件中读取数据:

4
192 48 206 37 56
123 35 321 21 41
251 42 442 32 33

第一个数字是候选(列)的总数,我需要存储该值以供其他用途。然后我需要将其余数据读入二维数组。我用我现在拥有的代码更新了我的代码,但它仍然无法正常工作。我不断收到错误 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;
}

}

【问题讨论】:

  • 定义“完全不工作”。怎么了?华夫饼会从屏幕上出来吗?首先,您忽略了candidates。其次,您只是在阅读第一行:fin.nextLine(); 应该在每次迭代中。
  • 收到错误 java.lang.NumberFormatException: For input string: "" after I enter the filename
  • 我怎么会忽略候选人?我不明白。
  • 您在循环中硬编码 5,而不是解析 candidates,这是要读取的预期行数。然后,您不会在每次迭代中阅读。
  • 啊,我明白了,谢谢。

标签: java arrays


【解决方案1】:

据我了解,您的主要任务是从文件中提取 整数 值并将其放入二维数组中。

我建议您参考 Oracle 网站上的 Scanner API Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

您可以在那里找到一些更适合您的任务的方法:

  1. nextInt() - 用于直接从文件中获取整数值
  2. hasNextLine() - 用于判断是否有下一行输入

假设candidates列数,它应该被视为整数,而不是字符串:

int candidates = fin.nextInt();

使用上述 Scanner 方法后,将不再需要从文件中获取 String 值,因此可以从源代码中完全删除 linenumbers 变量。

使用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
}

请记住,Java 数组不是动态可伸缩的

您的二维数组 - table 应该使用要放入其中的数据的确切大小进行初始化。

在您当前的示例中,直到文件末尾您才知道输入行的数量,因此正确初始化数组可能需要额外的操作。

【讨论】:

  • 帮了我一吨的家伙现在完美地工作了谢谢你的帮助
  • 很高兴听到 :) 干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 2014-04-06
相关资源
最近更新 更多