用java逐列求和

rickyhitman10
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)

{

//每个列的总和

}

帮帮我,谢谢

艾略特·新鲜

我会try-with-resources用来清理我ScannerFile另外,您可以Scannerline输入周围构造一个来获取您的int列(这不需要关闭,因为String无论如何都无法关闭它们)。就像是,

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)构造器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为了提高效率,您可能更喜欢使用Maplike

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章