Search code examples
javaarraysfilemaze

Java: txt file into a 2nd array


So, the first problem is how I can get the number of column from the file txt. The file is like that:

WWWSWW\n  
WWW___\n   
WWWWWW\n  
W_____\n  
WWW_WW\n  
W_____\n  
W_W_W\n  
WE____\n  

In this example I have 8 rows and 8 columns but I have to extract that from the file.

Another problem is I can't return the array to another class.

My code:

File file = new File("maze.txt");
Scanner scanner = new Scanner(file);
//contar as linhas
List<String> lines= 
Files.readAllLines(Paths.get("maze.txt"),Charset.defaultCharset());

int noOfLines=lines.size()-1;
char[][] myArray=new char[noOfLines][noOfLines];

//this read the file and make the array
for (int row = 0; scanner.hasNextLine() && row < noOfLines; row++) {
    char[] chars = scanner.nextLine().toCharArray();
    for (int i = 0; i < noOfLines && i < chars.length; i++) {
        myArray[row][i] = chars[i];

    }

}

Solution

  • I'd read the entire file as you did, and then just use Java 8's streaming capabilities to do all the heavy lifting for you:

    char[][] maze = lines.stream().map(String::toCharArray).toArray(char[][]::new);