【问题标题】:summing column by column in java在java中逐列求和
【发布时间】:2014-11-09 07:45:27
【问题描述】:
i have file txt in desktop :
1   5     23
2   5     25  
3   30    36

i want sum column by column 1 + 2 + 3 =... and 5 + 5...n and 23,...n

Scanner sc = new Scanner (file("patch");
while (sc.hasNextLine)

{

//每列总和

}

请帮帮我,谢谢

【问题讨论】:

  • 如果您知道每行有多少条目,您可以为总和创建一个int[]。然后在您读取每一行之后,对其进行拆分、解析并递增每个单独的总和。
  • @DavidWallace 您可以在不知道每行有多少条目的情况下使用二维数组,但它会变得更加复杂。
  • @MarshallTigerus 你可以,但你必须有点疯狂。如果你不知道每一行有多少条目,你应该使用ArrayList,以及一些关于何时添加新条目的奇特逻辑。
  • 有点疯狂或有点疯狂。除了数组之外,还有很多更好的处理方式。

标签: java arrays io


【解决方案1】:

我会使用try-with-resources 来清理我的Scanner,使用File。此外,您可以在输入的line 周围构造一个Scanner 以获取您的int 列(不需要关闭,因为String(s) 无论如何都不能关闭)。类似的,

try (Scanner sc = new Scanner(new File("patch"))) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        Scanner row = new Scanner(line);
        long sum = 0;
        int count = 0;
        while (row.hasNextInt()) {
            int val = row.nextInt();
            if (count == 0) {
                System.out.print(val);
            } else {
                System.out.printf(" + %d", val);
            }
            sum += val;
            count++;
        }
        System.out.println(" = " + sum);
    }
} catch (IOException e) {
    e.printStackTrace();
}

作为Scanner(String) Constructor Javadoc 文档

构造一个新的Scanner,生成从指定字符串扫描的值。

编辑总结列有点棘手,但您可以将所有内容读入多维 List<List<Integer>> 之类的

try (Scanner sc = new Scanner(new File("patch"))) {
    List<List<Integer>> rows = new ArrayList<>();
    int colCount = 0;
    while (sc.hasNextLine()) {
        List<Integer> al = new ArrayList<>();
        String line = sc.nextLine();
        Scanner row = new Scanner(line);
        colCount = 0;
        while (row.hasNextInt()) {
            colCount++;
            int val = row.nextInt();
            al.add(val);
        }
        rows.add(al);
    }
    for (int i = 0; i < colCount; i++) {
        long sum = 0;
        for (List<Integer> row : rows) {
            sum += row.get(i);
        }
        if (i != 0) {
            System.out.print("\t");
        }
        System.out.print(sum);
    }
    System.out.println();
} catch (IOException e) {
    e.printStackTrace();
}

编辑 2 为提高效率,您可能更喜欢使用 Map 之类的

try (Scanner sc = new Scanner(new File("patch"))) {
    Map<Integer, Integer> cols = new HashMap<>();
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        Scanner row = new Scanner(line);
        int colCount = 0;
        while (row.hasNextInt()) {
            int val = row.nextInt();
            if (cols.containsKey(colCount)) {
                val += cols.get(colCount);
            }
            cols.put(colCount, val);
            colCount++;
        }
    }
    for (int i : cols.values()) {
        System.out.printf("%d\t", i);
    }
    System.out.println();
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

  • 问题是对相同的列值求和。不是同一行。
  • 似乎效率不高,将整个矩阵保存在内存中。您只需要保留每列的运行总计。
【解决方案2】:

请找到代码。请通过 cmets。 这是为您的参考做的一种方式。我希望您尝试其他方法来提高您的知识,而不仅仅是使用此代码。

int sums[] = null;
    while (sc.hasNextLine())
    {
        String row = sc.next();// get first row
        String[] values = row.split(" ");// split by space
        if(null == sums)
        {
            sums = new int[values.length];// create sum array with first row size
        }
        int index = 0;
        for (String value : values)
        {
            sums[index] = sums[index]+Integer.parseInt(value);//adding current row value to current sum
            index++;
        }
    }
    if(null != sums)
    {
        int index=0;
        for (int sum : sums)
        {
            System.out.println("Sum of column "+index+" : "+sum);// Printing each column sum
            index++;
        }
    }

【讨论】:

    【解决方案3】:

    如果您的文件是 CSV 格式,则用逗号 (",") 分割行并根据分割数组长度查找列数。

    如下:

    String line = sc.next();
    String[] lineArr = line.split(",");
    int len = lineArr.length;
    

    创建大小为 len 的数组列表并将每个列字段存储在相应的数组列表中。 最后,最后对每个arraylist应用sum来计算每列值的总和。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多