gpt4 book ai didi

java - java中逐列求和

转载 作者:行者123 更新时间:2023-12-01 22:36:17 26 4
gpt4 key购买 nike

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)

{

//each sum by column

}

help me please thanks

最佳答案

我会使用 try-with-resources 清理我的Scanner使用File 。另外,您可以构造一个 Scanner周围line输入以获得您的 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) 构造函数Javadoc文档

Constructs a new Scanner that produces values scanned from the specified string.

编辑 对列进行求和有点棘手,但您可以将所有内容读入多维 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();
}

关于java - java中逐列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26826151/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com