【问题标题】:Turning text file into a 2d array将文本文件转换为二维数组
【发布时间】:2015-11-26 06:08:41
【问题描述】:

我需要获取一个如下所示的文本文件,并根据其中的数字创建一个二维数组。但是,它需要非常通用,以便它可以应用于条目比这个条目更多或更少的文本文件。

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

【问题讨论】:

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


    【解决方案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]);
     } 
    }
    

    【讨论】:

    • 我觉得我快要让它发挥作用了。我尝试了您的建议,目前在尝试解析整数时遇到错误,我不知道为什么。我将编辑上面的代码,向您展示我做了什么。并感谢到目前为止的帮助!
    • 我明白了!出于某种原因,我不得不在 .split(" ") 中用一个额外的空间隔开它,它开始工作了!非常感谢!
    • .split("\s+") 改用这个。如果您觉得有帮助,也请接受答案。
    猜你喜欢
    • 2015-05-28
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多