简体   繁体   English

Java:文本文件到二维数组

[英]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.文本文件中的每一行有 20 个字符。 5 lines. 5 行。

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.此外,我对扫描仪类不是很熟悉,所以如果 hasNextLine 和 hasNext 不适合我想要实现的目标,请告诉我。

I will personally use the BufferReader instance to take the object of each line in the textfile.我将亲自使用 BufferReader 实例来获取文本文件中每一行的对象。 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?使用迭代器获取每一行的实例后,您可以通过以下链接将该对象转换为 String 和 char: 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.另外,请确保 nextLine 是否为空。 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();
}

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

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