首页 > 解决方案 > 对如何将 txt 文件写入字符串然后将其转换为二维数组感到困惑

问题描述

所以我试图写一个看起来像这样的txt文件

8 7
1 1 1 1 1 1 1
1 0 0 0 e 1 1
1 0 1 0 0 1 1 
1 0 1 0 1 0 1 
1 0 0 0 0 0 1 
1 0 0 1 0 0 1 
1 0 1 0 1 s 1 
1 1 1 1 1 1 1 

而且我无法将前两个数字作为数组的大小,然后将其余数字转换为字符串,然后将该字符串转换为具有所有这些值的二维数组。谢谢!

while (input.hasNext()) {
    numRows = input.nextInt();
    numCols = input.nextInt();

    input.nextLine();

    String s = "";
    for (int i = 0; i < numRows; i++)
        s = s + input.nextLine();

    int place = 0;
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            maze[numRows][numCols] = String.valueOf(s.charAt(place));
            place++;
        }
    }
}

标签: java

解决方案


你没有索引。使用您已定义i的索引。j这是使用索引正确迭代的示例:

矩阵.txt

8 7
1 1 1 1 1 1 1
1 0 0 0 e 1 1
1 0 1 0 0 1 1 
1 0 1 0 1 0 1 
1 0 0 0 0 0 1 
1 0 0 1 0 0 1 
1 0 1 0 1 s 1 
1 1 1 1 1 1 1 

主.java

public class Main {
  public static void main(String[] args) throws IOException {
    char[][] matrix = null; // change to String[][] matrix = null; if you want Strings
    try (Scanner s = new Scanner(Path.of("matrix.txt"))) {
      int rows = s.nextInt();
      int cols = s.nextInt();
      s.nextLine();
      matrix = new char[rows][cols]; // change to matrix = new String[rows][cols];
      for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
          matrix[i][j] = s.next().charAt(0); // change to matrix[i][j] = s.next();
        }
      }
    }
    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
      }
      System.out.println();
    }
  }
}

输出:

1 1 1 1 1 1 1
1 0 0 0 e 1 1
1 0 1 0 0 1 1
1 0 1 0 1 0 1
1 0 0 0 0 0 1
1 0 0 1 0 0 1
1 0 1 0 1 s 1
1 1 1 1 1 1 1

我还为您想要 aString[]而不是 a的情况添加了建议char[]


推荐阅读