简体   繁体   中英

Java: Reading txt file into a 2D array

For homework, we have to read in a txt file which contains a map. 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.

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.

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.

// ...
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 . A Map is a totally different data structure. 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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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