简体   繁体   中英

Method to fill 2d array with text file

Currently I'm working on a project to create the game of life, however I'm getting stuck writing one of the first methods I have to use. Basically, it has to read in the text file and fill it in a 2d array. Right now I'm getting an error in the main that says "Exception in thread "main" java.util.NoSuchElementException: No line found." Any help would be greatly appreciated. By the way, I should mention that in the file I know the number of lines, but want to make it like i don't know the number of rows/cols.

import java.util.*;
import java.io.*;
public class Proj5testing {
public static void main (String[] args)throws IOException{
    Scanner inFile = new Scanner(new File("life4.txt"));
    System.out.print(readBoard("life4.txt"));

}

public static int[][] readBoard(String filename)throws IOException{
    int rows=0;
    Scanner inFile = new Scanner(new File(filename));
    while (inFile.hasNextLine()) {
          rows++;
          inFile.nextLine();
        }
    int cols=Integer.parseInt(inFile.nextLine());
    int[][] grid=new int[rows][cols];
    for(int i=0;i<grid.length;i++){
        for(int k=0;k<grid[rows].length;k++){
            grid[i][k]=inFile.nextInt();

        }
    }
    return grid
}
}

Look at this code:

while (inFile.hasNextLine()) {
    rows++;
    inFile.nextLine();
}

This will loop until there are no more lines. hasNextLine() will be false when the loop exits (or else the loop wouldn't exit).

Then immediately after, you call:

int cols=Integer.parseInt(inFile.nextLine());

But we already know for sure that there is no next line in the file! So of course it will throw an error.

Instead, you need to process each line within the loop. I don't know the exact structure of your file, but it would be something like this:

int[][] grid=new int[rows][cols];
int col = 0;
int row = 0;
while (inFile.hasNextInt()) {
    grid[col][row] = inFile.nextInt();
    col = col + 1;
    if (col == cols) { //wrap to the next row
        row = row + 1;
        col = 0;
    }
}

the problem is that you are trying to read the next line in the inFile but there is no next line since you already read all lines in the while loop.

You would have to redeclare the Scanner object to be able to read from the beginning again.

When your while loop ends, scanner has reached the end of file. So, there are no more lines (or ints) to read. To solve this, you can re-initialize the scanner before your for loop.

inFile = new Scanner(new File(filename));

There are some other problems with your code as well. Have a look at the below modified code (this would probably do what you want):

import java.util.*;
import java.io.*;

public class Proj5testing {

    public static void main (String[] args) throws IOException {
        // System.out.print(readBoard("life4.txt"));
        // this will just print a referenceId; if you want to print the contents, you need to write a loop to iterate over all the elements

        int[][] board = readBoard("life4.txt");
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[i].length; j++) {
                System.out.print(board[i][j]);
            }
            System.out.println();
        }
    }

    public static int[][] readBoard(String filename) throws IOException {
        int rows = 0;
        String line = "";
        Scanner inFile = new Scanner(new File(filename));
        while(inFile.hasNextLine()) {
            rows++;
            line = inFile.nextLine();
        }

        // int cols = line.split("\\s+").length;
        // assuming that the file has space-separated integers in different lines
        // e.g.
        // 0 0 1 0 1
        // 0 0 0 0 1
        // 1 1 1 1 1
        // since the file doesn't have space-separated integers, updating the answer

        int cols = line.length();
        // assuming that the file has lines in the following format
        // 001001001
        // 110011011

        inFile = new Scanner(new File(filename));
        // this will bring the scanner back to the start of the file

        int[][] grid = new int[rows][cols];
        for(int i = 0; i < rows; i++){
            line = inFile.nextLine();
            for(int k = 0; k < cols; k++){
                grid[i][k] = line.charAt(k) - '0';
            }
        }
        return grid;
    }
}

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