简体   繁体   English

读取文件并将其转换为Java中的二维数组

[英]reading a file and turning it into a 2-d array in java

I need to make a 20x45 array using a text file. 我需要使用文本文件制作20x45数组。 For example using a 3*5 array: 例如,使用3 * 5数组:

Text input from file: 来自文件的文本输入:
Four score and seven years ago 四分和七年前

The array (Using _ to indicate spaces): 数组(使用_表示空格):
F our _ F我们的_
score 得分
_ and _ _和_

I'll be transparent in saying I'm pretty much brand new to Java and I've been trying for a while and don't know where to begin. 我会坦率地说我是Java的新手,而且我已经尝试了一段时间,而且不知道从哪里开始。 I have gotten this code so far: 到目前为止,我已经获得了以下代码:

    // Create file instance.
    java.io.File file = new java.io.File("array.txt"); 

    int totalRow = 20;
    int totalColumn = 45;
    char[][] myArray = new char[totalRow][totalColumn];
    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];
            System.out.println(myArray[row][i]);
        }
        //System.out.println("");
    }

I have tried many different iterations and I'm stuck. 我尝试了许多不同的迭代,但遇到了麻烦。
Thanks in advance. 提前致谢。

The problem is that the first time scanner.nextLine().toCharArray(); 问题是第一次使用scanner.nextLine().toCharArray(); is ran, it reads the entire text because the file contains only one line. 运行后,它将读取整个文本,因为该文件仅包含一行。 However, in that loop your code only process the first row of the 2d array. 但是,在该循环中,您的代码仅处理2d数组的第一行。

for (int row = 0; scanner.hasNextLine() && row < totalRow; row++) {    
    char[] chars = scanner.nextLine().toCharArray(); //Notice this reads the entire text the first loop when row=0
    for (int i = 0; i < totalColumn && i < chars.length; i++) {
        //This loop fills the first row of the array when row=0
        myArray[row][i] = chars[i];
        System.out.println(myArray[row][i]);
    }
    //End of loop, the next time scanner.hasNextLine() returns false and loop terminates
}

To solve this problem, you should read chars outside of the loop (read it only once). 要解决此问题,您应该在循环外读取chars (仅读取一次)。 Then use a single index to iterate through the chars while iterating through the 2d array. 然后使用单个索引遍历char,同时遍历2d数组。

char[] chars = scanner.nextLine().toCharArray();
int i = 0;

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

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

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