如何对包含多行的文件中的一行整数求和 - Java

How to sum a row of integers from a file that contains multiple rows - Java

我正在尝试对文件中不同行中的数字求和。另外,我希望代码忽略每一行的第一个数字。

3 3 3 3
1 1 1 1 1
2 2  

根据这些数字,我想打印出 9、4 和 2。

而我得到的答案是 21,因为我显然用这段业余代码总结了所有内容:

  while(scan.hasNextInt())  
    {  
        a = a + scan.nextInt();
    } 
    System.out.println(a);

没有你的另一面代码,但我想我明白你想做什么。

所以你可以逐行获取所有内容,并且可以从第二个开始 object.Her 是代码:

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

如果输入来自控制台或System.in,我能够使用扫描仪而不是数组来获得所需的输出来保存行,或者System.in你必须在scan变量中考虑到这一点

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

结果

Line 3 3 3 3  : result 9
Line 1 1 1 1 1  : result 4
Line 2 2   : result 2

为了完整起见,流式解决方案。

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

这是 1 行:

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