Advertisement
Ligh7_of_H3av3n

02. Sum Numbers

May 27th, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. package Lekciq;
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.Scanner;
  6. import java.util.function.Function;
  7. import java.util.stream.Collectors;
  8.  
  9. public class SumNumbers {
  10.     public static void main(String[] args) {
  11.         Scanner scanner = new Scanner(System.in);
  12.  
  13.  
  14.         // Read input line
  15.         String input = scanner.nextLine();
  16.  
  17.         // Define a function to parse strings to integers
  18.         Function<String, Integer> parseInteger = Integer::parseInt;
  19.  
  20.         // Split the input into strings, parse them to integers, and collect into a list
  21.         List<Integer> numbers = Arrays.stream(input.split(", "))
  22.                 .map(parseInteger)
  23.                 .collect(Collectors.toList());
  24.  
  25.         // Calculate the count and the sum of the numbers
  26.         int count = numbers.size();
  27.         int sum = numbers.stream().mapToInt(Integer::intValue).sum();
  28.  
  29.         // Print the count and the sum
  30.         System.out.println("Count = " + count);
  31.         System.out.println("Sum = " + sum);
  32.     }
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement