簡體   English   中英

讀取文件並將其轉換為Java中的二維數組

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

我需要使用文本文件制作20x45數組。 例如,使用3 * 5數組:

來自文件的文本輸入:
四分和七年前

數組(使用_表示空格):
F我們的_
得分
_和_

我會坦率地說我是Java的新手,而且我已經嘗試了一段時間,而且不知道從哪里開始。 到目前為止,我已經獲得了以下代碼:

    // 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("");
    }

我嘗試了許多不同的迭代,但遇到了麻煩。
提前致謝。

問題是第一次使用scanner.nextLine().toCharArray(); 運行后,它將讀取整個文本,因為該文件僅包含一行。 但是,在該循環中,您的代碼僅處理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
}

要解決此問題,您應該在循環外讀取chars (僅讀取一次)。 然后使用單個索引遍歷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