Search code examples
javaarraysmultidimensional-arrayn-queenscharat

How do you scan a text file and convert it to a 2D char array?


I have been given text files and I am trying to convert them into a 2D char array for further use. What is happening is it appears to be taking the first indices and copying that over and over until it has reached the int size and it believes there is only one column. I wondered also if it has something to do with charAt as I am not familiar with it.

public static void main(String[] args) throws FileNotFoundException
    {
        System.out.println("Enter file path here!");
        Scanner input = new Scanner(System.in);
        File file = new File(input.nextLine());
        Scanner inputFile = new Scanner(file);
        int size = inputFile.nextInt();
        char[][] testBoard = new char[size][size];
        for (int i = 0; i < size; i++)
        {
            String line = inputFile.next();
            for (int j = 0; j < size; j++)
            {
                testBoard[i][j]= line.charAt(i);
                System.out.println(testBoard[i][j]);
            }
        }

An example of a file given is

4
BQBB
BBBQ
QBBB
BBQB

Please help its messing up my code!


Solution

  • Instead of testBoard[i][j]= line.charAt(i); try testBoard[i][j]= line.charAt(j);