Advertisement
desislava_topuzakova

1. Sum Lines

Jan 22nd, 2022
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. package StreamsFilesDirectories_Exercise;
  2.  
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.Path;
  6. import java.util.List;
  7. import java.util.Scanner;
  8.  
  9. public class SumLines_01 {
  10.     public static void main(String[] args) throws IOException {
  11.         Scanner scanner = new Scanner(System.in);
  12.         //1. прочетем всички редове от файла
  13.         //2. обходим всеки един ред -> намирам сумата от ascii -> print сумата
  14.         String path = "C:\\Users\\I353529\\Desktop\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\input.txt";
  15.         List<String> allLines = Files.readAllLines(Path.of(path));
  16.  
  17.         //начин 1:
  18.         /*for (String line : allLines) {
  19.             int sum = 0; //сумата за всеки един ред
  20.            // намирам сумата от ascii -> print сумата
  21.             for (int index = 0; index < line.length(); index++) {
  22.                 char currentSymbol = line.charAt(index);
  23.                 sum += currentSymbol;
  24.             }
  25.             System.out.println(sum);
  26.         }*/
  27.  
  28.         //начин 2
  29.         allLines.stream()
  30.                 .map(line -> line.toCharArray())  //"Ivan" -> ['I', 'v', 'a', 'n']
  31.                 .forEach(arr -> {
  32.                     int sum = 0;
  33.                     for (char symbol : arr ) {
  34.                         sum += symbol;
  35.                     }
  36.                     System.out.println(sum);
  37.                 });
  38.     }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement