繁体   English   中英

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

[英]Turning text file into a 2d array

我需要一个像下面的文本文件,并根据其中的数字创建一个二维数组。 但是,它必须非常笼统,以便它可以应用于条目比该条目更多或更少的文本文件。

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]);
         } 
      }
   }
}

当您要创建一个大小为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]);
 } 
}

暂无
暂无

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

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