简体   繁体   中英

Java: Text file to 2D array

I need to take a text file and initialize a 2d array from the text in that file. Each line in the text file has 20 characters. 5 lines.

So far all I have is

int totalRow = 5;
int totalColumn = 20
char[][] myArray = new char[totalRow][totalColumn];
File file = new File("test.txt");
Scanner scanner = new Scanner(file);

int row = 0;
int column = 0;

    while (scanner.hasNextLine()){
        while (scanner.hasNext()){
            myArray[row][column] = scanner.next();
            column++;
        }
    row++;
    }

The problem I am having at the moment is that I get error: string cannot be converted to char

Additionally I am not very familiar with the scanner class, so if hasNextLine, and hasNext are not appropriate for what I am trying to achieve, please let me know.

I will personally use the BufferReader instance to take the object of each line in the textfile. After you get the instance of each line by using iterator, you can convert that object into String and char by following this link: How to convert/parse from String to char in java? . If you do not know how to do already.

Also, please make sure that if the nextLine is null. You want to exit out of the iterator. You can put these char into the 2-D array fashion as you wish. I hope this helps.

Not the most efficient solution, but without deviating too much from the original version, this should do what you want:

int totalRow = 5;
int totalColumn = 20;
char[][] myArray = new char[totalRow][totalColumn];
File file = new File("test.txt");
Scanner scanner = new Scanner(file);


for (int row = 0; scanner.hasNextLine() && row < totalRow; row++) {
    char[] chars = scanner.nextLine().toCharArray();
    for (int i = 0; i < totalColumn && i < chars.length; i++) {
        myArray[row][i] = chars[i];
    }
}

EDIT: On second thought, if you're confident about the column width, you can further simplify the code:

int totalRow = 5;
char[][] myArray = new char[totalRow][];
File file = new File("test.txt");
Scanner scanner = new Scanner(file);

for (int row = 0; scanner.hasNextLine() && row < totalRow; row++) {
    myArray[row] = scanner.nextLine().toCharArray();
}

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