【问题标题】:How to sort a large text file into a multi-dimensional array?如何将大文本文件排序为多维数组?
【发布时间】:2013-05-12 13:45:30
【问题描述】:

我正在尝试读取一个大文本文件并使用scanner() 将其排序为一个3D 数组,但我认为该数组没有被填充,并且我不断收到错误java.lang.NullPointerException,但我怀疑那里问题不止于此。

我目前正在尝试使用嵌套的 for 循环来排序年、月和每个日期。

我想做的另一件事是将数组从String 更改为int,但它没有。

这是我的代码:

public class GetData {

    public String[][][] sortedData;

    private Scanner rainFile;

    //method for opening the file
    public void openFile() {

        try{
            rainFile = new Scanner(new File("myfile.txt"));
        }
        catch(Exception e){
            System.out.println("Could not find file");
        }
    }

    //method for reading the file
    public void readFile(){

        int month = 0;
        int day = 0;

        //this loop sorts each year
        for(int l = 0; l < 34; l++){
            String a = rainFile.next();
            sortedData[l][month][day] = a;

                //this loop sorts every month of each year
                for(int i = 0; i < 12; i++){
                    String b = rainFile.next();
                    sortedData[l][i][day] = b;
                    month++;

                        //this loop sorts each individual entry of every month
                        for(int j = 0; j < 31; j++){
                            String c = rainFile.next();
                            sortedData[l][i][j] = c;
                            day++;
                        }
                    }        
                }

        }

        //close the file once it's been used
        public void closeFile(){
            rainFile.close();
        }

        //test method to see if array is full
        public void arrayTest(){
            System.out.print(sortedData[1][1][1]);
        }
}

非常感谢。

【问题讨论】:

    标签: java arrays sorting multidimensional-array java.util.scanner


    【解决方案1】:

    先创建实例

    public String[][][] sortedData = new String[n][n2][n3]; //n1 n2 n3 dimension size
    

    【讨论】:

    • 如果我有 34 年 408 个月和 12648 天,会是 public String[][][] sortedData = new String[34][408][12648]; 还是 public String[][][] sortedData = new String[34][12][31];?出于某种原因,前者似乎过分了。编辑:前者有效,非常感谢!
    • 不,你需要 [34][12][31]。那么你的数组将有 34 * 12 * 31 个元素。 34年每一年有12个月,每个月有31天
    • 我刚把它改成[34][12][31]又遇到了异常。我以为Java中的多维数组不是真正的多维数组?
    • @JoshJahans 那是因为您使用可变天作为索引。
    • 我应该改用什么?
    【解决方案2】:

    你忘了这个:

    sortedData = new String[34][12][31];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多