1

对于家庭作业,我们必须读入一个包含地图的 txt 文件。使用地图,我们应该读取其内容并将它们放入二维数组中。

我已经设法将文件读入一维字符串数组列表,但我遇到的问题是将其转换为二维字符数组。

这是我到目前为止在构造函数中的内容:

try{

  Scanner file=new Scanner (new File(filename));

    while(file.hasNextLine()){

        ArrayList<String> lines= new ArrayList<String>();

        String line= file.nextLine();

        lines.add(line);    

        map=new char[lines.size()][];

    }
}
catch (IOException e){
    System.out.println("IOException");
}

当我打印出 lines.size() 时,它打印出 1 但是当我查看文件时它有 10。

提前致谢。

4

2 回答 2

4

您必须在循环外创建列表。在您的实际实现中,您为每个新行创建一个新列表,因此它的大小始终为 1。

// ...
Scanner file = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();  // <- declare lines as List
while(file.hasNextLine()) {
// ...

顺便说一句 - 我不会命名char[][]变量map。Map 是一种完全不同的数据结构。这是一个数组,如果您在循环内创建,那么您可能会遇到与列表相同的问题。但现在你应该知道一个快速修复;)

于 2012-09-26T06:38:11.997 回答
0

更改代码如下:

public static void main(String[] args) {
        char[][] map = null;
        try {
            Scanner file = new Scanner(new File("textfile.txt"));
            ArrayList<String> lines = new ArrayList<String>();
            while (file.hasNextLine()) {
                String line = file.nextLine();
                lines.add(line);
            }
            map = new char[lines.size()][];
        } catch (IOException e) {
            System.out.println("IOException");
        }
        System.out.println(map.length);
    }
于 2012-09-26T06:44:57.807 回答