简体   繁体   English

Java:将txt文件读入2D数组

[英]Java: Reading txt file into a 2D array

For homework, we have to read in a txt file which contains a map. 对于家庭作业,我们必须读入包含地图的txt文件。 With the map we are supposed to read in its contents and place them into a two dimensional array. 使用地图,我们应该读取其内容并将它们放入二维数组中。

I've managed to read the file into a one dimensional String ArrayList, but the problem I am having is with converting that into a two dimensional char array. 我已经设法将文件读入一维String ArrayList,但我遇到的问题是将其转换为二维char数组。

This is what I have so far in the constructor: 这是我到目前为止在构造函数中所拥有的:

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");
}

When I print out the lines.size() it prints out 1 but when I look at the file it has 10. 当我打印出lines.size()时,它打印出来1但是当我查看文件时它有10个。

Thanks in advance. 提前致谢。

You have to create the list outside the loop. 您必须在循环创建列表。 With your actual implementation, you create a new list for each new line, so it will always have size 1. 通过实际实现,您可以为每个新行创建一个新列表,因此它的大小始终为1。

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

BTW - I wouldn't name the char[][] variable map . BTW - 我不会命名char[][]变量map A Map is a totally different data structure. Map是一种完全不同的数据结构。 This is an array, and if you create in inside the loop, then you may encounter the same problems like you have with the list. 这是一个数组,如果你在循环内创建,那么你可能会遇到与列表一样的问题。 But now you should know a quick fix ;) 但现在你应该知道一个快速修复;)

Change the code as following: 更改代码如下:

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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM