简体   繁体   English

用文本文件填充二维数组的方法

[英]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. 基本上,它必须读取文本文件并将其填充为2d数组。 Right now I'm getting an error in the main that says "Exception in thread "main" java.util.NoSuchElementException: No line found." 现在,我在主程序中得到一个错误,提示“线程“主程序中的异常” java.util.NoSuchElementException:找不到行。 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). 当循环退出时(否则循环不会退出), hasNextLine()将为false。

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. 问题是您正在尝试读取inFile的下一行,但是由于您已经在while循环中读取了所有行,所以没有下一行。

You would have to redeclare the Scanner object to be able to read from the beginning again. 您必须重新声明Scanner对象才能再次从头读取。

When your while loop ends, scanner has reached the end of file. 当while循环结束时,扫描仪已到达文件末尾。 So, there are no more lines (or ints) to read. 因此,没有更多的行(或整数)要读取。 To solve this, you can re-initialize the scanner before your for loop. 要解决此问题,可以在for循环之前重新初始化扫描仪。

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;
    }
}

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

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