txt文件转换为2D数组

时间:2019-05-01 20:33:49

标签: java

我应该从填充有15个X和O的.txt文件中转换第二行,并将其打印到Java中的2D数组中。

这是我的.txt文件中的一维数组。

XOXOX
XOOXX
XXXOO
XXOOO
XXXXO
OOOOX
XOOXX
OOXXO
OXOXO
OXXXO
public static void main(String[] args) throws FileNotFoundException {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter the input filename ");
    String inputFile = in.next();
    Scanner inFile = new Scanner(new File(inputFile));
    String line=inFile.nextLine();
    line.toUpperCase();
    String array[] = line.split("X");
    System.out.println(array[0]+  " " + array [1]);
    String arrayE1 = array[0];
    String arrayE2 = array[1];
    Integer.parseInt(arrayE1);
    Integer.parseInt(arrayE2);
    String line2 = inFile.next();
    System.out.println(line2);

    char [][] MovieTheater = new char [Integer.parseInt(arrayE1)][Integer.parseInt(arrayE2)];

    int k = 0;
    for (int i = 0; i < Integer.parseInt(arrayE1); i++) {
        for (int j = 0; i < Integer.parseInt(arrayE2); j++) {
            MovieTheater[i][j] = line2.charAt(k++);
        }
        System.out.println("");
    }
    inFile.close();
}

1 个答案:

答案 0 :(得分:0)

您可以使用Files.lines()来读取文件中的所有行,并使用String.toCharArray()来获取每行中的所有字符:

try (Stream<String> lines = Files.lines(Paths.get(inputFile))) {
    char[][] movieTheater = lines
            .map(String::toCharArray)
            .toArray(char[][]::new);
    System.out.println(Arrays.deepToString(movieTheater));
}

结果将是这个2D数组:

[
    [X, O, X, O, X], [X, O, O, X, X], 
    [X, X, X, O, O], [X, X, O, O, O], 
    [X, X, X, X, O], [O, O, O, O, X], 
    [X, O, O, X, X], [O, O, X, X, O], 
    [O, X, O, X, O], [O, X, X, X, O]
]