将文本文件转换为二维数组

时间:2015-11-26 06:08:41

标签: java arrays file-io multidimensional-array input

我需要获取类似下面的文本文件,并从其中的数字创建一个二维数组。但是,它需要非常通用,以便它可以应用于包含比此更多或更少条目的文本文件。

1 1 11  
1 2 32  
1 4 23  
2 2 24  
2 5 45  
3 1 16  
3 2 37  
3 3 50  
3 4 79  
3 5 68  
4 4 33  
4 5 67  
1 1 75  
1 4 65  
2 1 26  
2 3 89  
2 5 74  

这是我到目前为止所做的,但是当我打印它时它只给了我全部的零。

import java.util.*;

public class MySales11 {
   //variables
   private ArrayList<String> list = new ArrayList<>();
   private int numberOfEntries;
   private int [][] allSales;

   //constructor
   public MySales11 (Scanner scan) {
      //scan and find # of entries
      while (scan.hasNext()){
         String line = scan.nextLine();
         list.add(line);
      }
      //define size of AllSales array
      allSales = new int[list.size()][3];
      //populate AllSales array with list ArrayList
      for(int a = 0; a < allSales.length; a++){
         String[] tokens = list.get(a).split(" ");
         for(int b = 0; b < tokens.length; b++){
              allSales[a][b] = Integer.parseInt(tokens[b]);
         } 
      }
   }
}

1 个答案:

答案 0 :(得分:1)

如果要创建大小为numOfEntries的数组,请阅读所有行。

while (scan.hasNext()) {
    scan.nextLine();
    numberOfEntries++;//this reads all the lines but never stores
}
allSales = new int[numberOfEntries][3];
while (scan.hasNext()) {//input is empty
//the execution never comes here.
}

现在输入为空。所以它永远不会为数组添加值。

您可以使用动态arrayList - 无需计算行数。

ArrayList<String> list = new ArrayList();
while (scan.hasNext()) {
  String s = scan.nextLine();
  list.add(s);
}

int [][] myArray = new int[list.size()][3];

for(int i = 0; i < myArray.length; ++i)
{
 String[] tokens = list.get(i).split("\\s+");//extra spaces
 for(int j = 0; j < tokens.length; ++j)
 {
   myArray[i][j] = Integer.parseInt(tokens[j]);
 } 
}
相关问题