简体   繁体   English

使用扫描仪从 txt 文件中读取字符并添加到二维数组

[英]Reading char with scanner from txt file and adding to a 2d array

I have a txt file that I am trying to read with the scanner class.我有一个 txt 文件,我试图用扫描仪 class 读取它。

I am using a double for loop to read the file and at it to a 2d array.我正在使用双循环来读取文件并将其写入二维数组。

The file looks like this:该文件如下所示:

3 3. R #. 3 3. R #. . . #. #. . . # #

the first line is the length and width of the 2d array respectively.第一行分别是二维数组的长度和宽度。

I got this working were it reads a similar txt file but instead of char it has int like this:如果它读取了一个类似的 txt 文件,但它不是 char 它有这样的 int,我得到了这个工作:

3 3 1 0 1 1 1 1 0 0 1 3 3 1 0 1 1 1 1 0 0 1

The method I am using here looks like this:我在这里使用的方法如下所示:

readFile(String filename){
  Scanner scan = new Scanner(new File(filename));
  // read the first two numbers in the file for the size of the array
  int numberRows = scan.nextInt();
  int numberColumns = scan.nextInt();

  char[][] grid = new char[numberRows][numberColums];
  for (int i = 0; i < numberRows; i++) {
      for (int j = 0; j < numberColumns; j++) {
           grid[i][j] = scan.next().charAt(0);
      }
   }
}

I would expect this to work the same as when using char instead of int.我希望这与使用 char 而不是 int 时的工作方式相同。

However I get an error NoSuchElementException when scan.next().charAt(0) actually runs trying to read the char from the txt file.但是,当 scan.next().charAt(0) 实际运行试图从 txt 文件中读取字符时,我收到错误 NoSuchElementException。

Am I trying to read strings instead of chars?我是否试图读取字符串而不是字符? I would assume that a single character would be read as a char by java scanner class.我假设 java 扫描仪 class 会将单个字符读取为字符。

Scanner.next() always returns a String . Scanner.next()总是返回一个String Please check https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html for more information.请查看https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html了解更多信息。 Before performing any operation on scan.next() eg scan.next().charAt(0) , you should check if (scan.hasNext()) condition.在对scan.next()执行任何操作之前,例如scan.next().charAt(0) ,您应该检查if (scan.hasNext())条件。

Let's open javadoc for Scanner#next method.让我们为 Scanner#next 方法打开javadoc
It states "Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern."它声明“从这个扫描器中查找并返回下一个完整的标记。一个完整的标记之前和之后是匹配分隔符模式的输入。”
Also it states that NoSuchElementException is generated if no more tokens are available.它还指出,如果没有更多可用的令牌,则会生成 NoSuchElementException。
At this moment we know why you get this exception.此刻,我们知道您为什么会收到此异常。
next method is usually used together with useDelimiter method that sets mentioned pattern. next 方法通常与设置提到的模式的 useDelimiter 方法一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM