簡體   English   中英

Java文件到二維數組

[英]Java file to 2D array

我正在嘗試從.txt文件創建2D數組,其中.txt文件看起來像這樣:

xxxx            
xxxx                 
xxxx                 
xxxx                

或類似這樣的東西:

xxx
xxx
xxx

因此,我需要處理2D數組的多個大小(注意:每個2D數組並不總是等於x和y尺寸)。 是否有初始化數組,或獲得每行的字符/字母/數字和列數的方法? 我不想使用一般性聲明,例如:

String[][] myArray = new Array[100][100];

然后使用Filewriter和Scanner類填充數組看起來像這樣嗎?

File f = new File(filename);
Scanner input = new Scanner(f);
for(int i = 0; i < myArray[0][].length; i++){
  for(int j = 0; j < myArray[][0].length, j++){
    myArray[i][j] = input.nextLine();
  }
}

在我看來,您有幾種選擇:

  1. 遍歷文件兩次,第一次獲取數組參數,或者
  2. 對其進行一次迭代,但填寫List<List<SomeType>>可能List<List<SomeType>>您的列表實例化為ArrayLists。 后者將在短期和長期內為您提供更大的靈活性。
  3. (根據MadProgrammer),第三個選項是重組文件,以提供決定數組大小所需的元數據。

例如,使用您的代碼,

  File f = new File(filename);
  Scanner input = new Scanner(f);
  List<List<String>> nestedLists = new ArrayList<>();
  while (input.hasNextLine()) {
     String line = input.nextLine();
     List<String> innerList = new ArrayList<>();
     Scanner innerScanner = new Scanner(line);
     while (innerScanner.hasNext()) {
        innerList.add(innerScanner.next());
     }
     nestedLists.add(innerList);
     innerScanner.close();
  }
  input.close();

Java Matrix可以根據您的大小要求設置每一行(這是一個數組)。

您可以使用: ArrayUtils.add(char[] array, char element) //static method但在此之前,您需要檢查文件行長度

要么,您還可以使用ArrayList>作為保存數據的集合

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM