简体   繁体   English

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

[英]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.

相关问题 如何对从Java控制台读取的多个整数求和? - How to sum multiple integers read from the console in Java? Java:如何检查扫描程序以查看文件是否包含整数或单词? - Java: How to check with a scanner to see if a file contains integers or words? 读取一个csv文件(包含字符,整数和特殊符号),并在Java中从中提取整数 - reading a csv file (which contains characters, integers and special symbols ) and extracting integers from it in java 如何从 Java 读取 csv 文件并在每行中添加整数(将字符串转换为整数) - how to read the csv file from Java and add the integers in each row (convert string to int) 从每行的文本文件中求和整数-java - Summing integers from a text file in each row - java 如果该行包含 java 中的某个数据,如何从 csv 文件中删除该行 - How to remove a row from a csv file if that row contains a certain data in java 如何用Java解析File中的Integer? - How to parse Integers from File in Java? 如何从Java文件中读取整数 - How to read in integers from a file in Java 如何从包含二维数组的.txt文件中读取整数,我得到了java.util.InputMismatchException - How to read the integers from the .txt file which contains 2-D array, i am getting java.util.InputMismatchException 如何比较 JAVA 中包含整数的字符串 - How to compare string which contains integers in JAVA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM