【问题标题】:How can I read a specifc column from a text file and calculate the average of this column?如何从文本文件中读取特定列并计算该列的平均值?
【发布时间】:2016-02-21 12:37:00
【问题描述】:

我对我目前正在做的一个 java 练习有点卡住了。我有一个这种格式的文本文件:

Quio Kla,2221,3.6 哇,3332,9.3 邹头,5556,9.7 弗洛宝,8766,8.1 安迪糖果,3339,6.8

我现在想计算整个第三列的平均值,但我必须先提取我相信的数据并将其存储在一个数组中。我能够使用缓冲读取器读取所有数据并在控制台中打印出整个文件,但这并没有让我更接近将它放入数组中。任何关于如何使用缓冲读取器将文本文件的特定列读取到数组中的任何建议都将受到高度赞赏。

非常感谢您。

【问题讨论】:

    标签: java arrays file


    【解决方案1】:

    您可以使用这部分代码拆分文本文件:

    BufferedReader in = null;
    try {
    in = new BufferedReader(new FileReader("textfile.txt"));
    String read = null;
        while ((read = in.readLine()) != null) {
            String[] splited = read.split(",");
            for (String part : splited) {
                System.out.println(part);
            }
        }
    } catch (IOException e) {
    System.out.println("There was a problem: " + e);
    e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
    }
    

    然后您将在数组part 中拥有所有列。

    【讨论】:

      【解决方案2】:

      这绝对不是最好的解决方案,但对你来说应该足够了

      BufferedReader input = new BufferedReader(new FileReader("/file"));
                      int numOfColumn = 2;
                      String line = "";
                      ArrayList<Integer>lines =  new ArrayList<>();
                      while ((line = input.readLine()) != null) {
                          lines.add(Integer.valueOf(line.split(",")[numOfColumn-1]));
                      }
                      long sum =0L;
                      for(int j:lines){
                          sum+=j;
                      }
                      int avg = (int)sum/lines.size();
      

      【讨论】:

        【解决方案3】:

        我将假设每个数据集都由文本文件中的换行符分隔。

        ArrayList<Double> thirdColumn = new ArrayList<>();
        BufferedReader in = null;
        String line=null;
        
        //initialize your reader here
        
        while ((line = in.readLine())!=null){
        
            String[] split = line.split(",");
        
            if (split.length>2)
                thirdColumn.add(Double.parseDouble(split[2]));
        }
        

        在 while 循环结束时,您应该准备好 thirdColumn ArrayList 并填充所需的数据。

        假设您的数据集具有以下标准格式。

        字符串、整数、双精度

        所以很自然地,用逗号分割应该给出一个长度为 3 的字符串数组,其中索引 2 处的字符串包含您的第三列数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-08
          • 2020-08-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多