简体   繁体   中英

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.

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 #. . #. . #

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:

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.

However I get an error NoSuchElementException when scan.next().charAt(0) actually runs trying to read the char from the txt file.

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.

Scanner.next() always returns a String . Please check https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html for more information. Before performing any operation on scan.next() eg scan.next().charAt(0) , you should check if (scan.hasNext()) condition.

Let's open javadoc for Scanner#next method.
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.
At this moment we know why you get this exception.
next method is usually used together with useDelimiter method that sets mentioned pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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