布尔2d数组文本文件

时间:2017-04-19 14:15:09

标签: java

我需要从文本文件中读取一系列#和空格,然后将其打印为迷宫。

public static void readMaze() throws FileNotFoundException{
  String fileName = "path/maze.txt";
  Scanner input = new Scanner(new File(fileName));

  int x = 0;
  String columns = "";
  while (input.hasNextLine()){
    x++;
    columns = input.nextLine();
  }
  int col = columns.length();
  boolean maze[][] = new boolean[x][col];
}

所以我得到了行数(x)和迷宫将拥有的列数。

下一步是创建一个布尔数组,每个“#”的值为true,文件中的每个空格都为false,我不知道如何执行此操作。

while (input.hasNextLine()){
  columns = input.nextLine();
  for (int c = 0; c < columns.length();c++){

    if (c == '#'){
       add true;
    }
    else{
      add false;
    }
  }
}

这是下一部分,但我不确定我需要放入for循环,我们将非常感谢指导。

3 个答案:

答案 0 :(得分:0)

你的谜题中唯一缺失的部分就是这个

int row = 0;
while (input.hasNextLine()){
    columns = input.nextLine();
    for (int c = 0; c < columns.length();c++){
        c = columns.charAt(c); 
        if (c == '#'){
             result[row, c] = true;
        }
        else{
            result[row, c] = false; // not even needed, false is the default value ;)
        }
    row ++;
    }

答案 1 :(得分:0)

应该更好用以下内容:

ArrayList<Boolean> returnArray = new ArrayList<Boolean>()
for (int c = 0; c < columns.length();c++){

            if (columns[c].equals("#")){
                 returnArray.add(true);
            }
            else{
                returnArray.add(false);
            }
        }

return returnArray.hasArray();

答案 2 :(得分:0)

    int i = 0;
    while(input.hasNextLine())
    {
        row = input.nextLine();
        String[] row_temp = row.split("(?!^)");
        int row_length = row_temp.length();
        for(int j=0; j<row_length; j++){

            if(row_temp[j].matches("#")){
                maze[i][j] = true;
            }
            else{
                maze[i][j] = false;
            }


        }
        i++;
    }