[英]How to sum a row of integers from a file that contains multiple rows - Java
I am trying to sum numbers in separate lines from a file.我正在尝试对文件中不同行中的数字求和。 In addition, I would like the code to ignore the first number of every line.
此外,我希望代码忽略每行的第一个数字。
3 3 3 3
1 1 1 1 1
2 2
From these numbers I would like to print out 9, 4 and 2.根据这些数字,我想打印出 9、4 和 2。
Whereas I am getting an answer of 21 as I sum everything apparently with this amateur piece of code:而我得到的答案是 21,因为我显然用这段业余代码总结了所有内容:
while(scan.hasNextInt())
{
a = a + scan.nextInt();
}
System.out.println(a);
String input = "3 3 3 3\n1 1 1 1 1\n2 2";
Scanner scan = new Scanner(input);
while(scan.hasNextLine()) {
Scanner line = new Scanner(scan.nextLine());
int calculation = 0;
for(int i = 0;line.hasNextInt();i++) {
if(i>0) {
calculation = calculation+line.nextInt();
}else {
line.nextInt();
}
}
System.out.println(calculation);
}
I was able to get your required output using scanners instead of an array to save the lines if the input is from the console or System.in
youll have to account for that in the scan
variable如果输入来自控制台或
System.in
,我能够使用扫描仪而不是数组来获取所需的 output 来保存行。在你必须在scan
变量中考虑到这一点
Without your other side of codes but I think i understood what you'r trying to do.没有你的代码的另一面,但我想我明白你想做什么。
So you can take all the line by line and can start from second object.Her is the code:所以你可以逐行获取所有内容,可以从第二个 object 开始。她的代码是:
String line;
while((line = scan.nextLine() != null)) {
String[] lines = line.split(" ");
int total = 0;
for(int i = 1; i < lines.length; i++) {
total += Integer.parseInt(lines[i]);
}
System.out.println(total);
}
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("D:\\data.txt"));
for (String line : lines) {
String[] numbers = line.split("\\s");
int result = 0;
for(int i=1 ; i<numbers.length ; i++) {
result = result + Integer.parseInt(numbers[i]);
}
System.out.println("Line "+line+" : result "+ result);
}
}
result结果
Line 3 3 3 3 : result 9
Line 1 1 1 1 1 : result 4
Line 2 2 : result 2
And for completeness, a stream solution.为了完整起见,一个 stream 解决方案。
try {
// read in the lines and stream them
Files.lines(Path.of("f:/source.txt"))
// split the lines on spaces and stream the tokens
.map(line -> Arrays.stream(line.split("\\s+"))
// skip the first one
.skip(1)
// convert each token to an int
.mapToInt(Integer::parseInt)
// sum them
.sum())
// and print each sum
.forEach(System.out::println);
// catch and print any exceptions.
} catch (Exception e) {
e.printStackTrace();
}
Here's a 1-liner:这是一个 1-liner:
Files.readAllLines(Paths.get("D:/data.txt")).stream()
.map(line -> line.split(" "))
.map(Arrays::stream)
.mapToInt(stream -> stream.skip(1).mapToInt(Integer::parseInt),sum())
.forEach(System.out::println);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.