如何从文本文件中读取游戏板并将其转换为2D数组

问题描述 投票:-1回答:1

我必须阅读的董事会示例是这样的:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9lMkZRRy5wbmcifQ==” alt =“文本文件中的示例板”>“>

现在,“测试文件”只是板子的名称,它不会存储在阵列中。 “ 3 3”部分指定了电路板的尺寸,但也不会读入阵列。我需要读入数组的唯一位是这些行下面的字符。

这是我的代码:

public static void main(String[] args) throws IllegalStateException {

    int lineCount = 0;
    String[] rowN = null;

    try {

        Scanner boardInput = new Scanner(new File(args[0]));
        Scanner movesInput = new Scanner(new File(args[1]));

        col = boardInput.nextLine().split("").length; // counts the columns

        while (boardInput.hasNextLine()) { // iterates through board file

            rows++; // counts the rows

        }

        rows -= 2;
        String line = boardInput.nextLine();
        while(boardInput.hasNextLine()){

            if (lineCount > 1){

                 rowN = line.split("");
                 boardArray[lineCount-2] = rowN;
                 line = boardInput.nextLine();
                 lineCount++;


            }



        }

        System.out.println(Arrays.deepToString(boardArray));


        //playGame();

        boardInput.close();
        movesInput.close();

    } catch (Exception e) {

        e.printStackTrace();

    }

}

我觉得只有解释自己尝试背后的原因,这才有帮助。首先,我仅通过阅读其中的一行并获取其长度就设法找到了no.columns。其次,我设法通过遍历文件并计算行数来找到行数,然后减去2,以解决先前不需要的行数。这样,我得到了数组的尺寸;行和列。

下一部分,我发现更加棘手。我再次遍历文件,并检查变量lineCount是否大于1(以解释前面的行)。如果是这样,则指定数组rowN

等于我们想要的第一行字符的不同字符。在这之后,我陷入了困境,现在已经尝试了一段时间以解决此问题。谢谢您的时间!

我必须从中读取板的一个示例是这样的:现在,“测试文件”只是板的名称,并且不会存储在数组中。 “ 3 3”部分指定...

java multidimensional-array text-files
1个回答
0
投票

我不明白您为什么尝试从文本文件的尺寸中获取电路板的尺寸,如果您可以直接从所述文件中读取它的尺寸。在您看来,您当前尝试执行的方式似乎包含一些错误:

© www.soinside.com 2019 - 2024. All rights reserved.