如何使用列表填充网格?

时间:2019-05-02 01:40:03

标签: java list

我正在尝试获取此代码以读取文本文件,然后使用该文件中的数字填充15x15的网格。它所做的只是用0填充网格。我不确定如何解决它,但我认为问题出在我如何在循环中使用list.indexOf()。

我尝试过切换为使用list.get(i)或使用j,但这并没有达到我需要的方式。

public Grid(String fileName) throws FileNotFoundException {
    //reading file using scanner
    Scanner sc = new Scanner(new File(fileName));
    //first number is the dimension for rows
    this.rows = sc.nextInt();
    //since it is square matrix second dimension is same as first
    this.cols = this.rows;
    grid = new boolean[rows][cols];

    String longNumber = sc.next();
    List<Integer> list = new ArrayList<>();
    for(char ch : longNumber.toCharArray()) {
        list.add( Integer.valueOf(String.valueOf(ch)));
    }

    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++) {
            //reading from file 1 and 0 if 1 then store true else store false in grid
            if (list.indexOf(i) == 1)
                grid[i][j] = true;
            else
                grid[i][j] = false;
        }
}

我得到的输出显示一个15x15的0块,而不是从文本文件中读取的1和0。应该读入并显示该文本文件(以及斑点或成簇的1的计数),但这没有发生。如果您需要其余的代码,请告诉我。我需要读入一个文件,该文件包含一个用于构成网格的int(15),然后是15行的1和0行,当程序正常运行时,应该以相同的方式显示。

1 个答案:

答案 0 :(得分:0)

为什么要将其转换为List<Integer>?您可以简单地使用从文件中获取的String

对于每一行,您都必须获得一个String,然后对于每个String,您可以执行charAt()以检查其中的字符并存储{{ 1}}或true中的false

代码将如下所示:

grid

请注意,我已将this.rows = sc.nextInt(); //since it is square matrix second dimension is same as first this.cols = this.rows; grid = new boolean[rows][cols]; for (int i = 0; i < rows; i++) { String longNumber = sc.next(); for (int j = 0; j < cols; j++) { //reading from file 1 and 0 if 1 then store true else store false in grid grid[i][j] = (longNumber.charAt(j) == 1); } } 放在了外部循环中。

HTH