IrinaIgnatova

Matrix-Четене на матрица като списък от списъци

Oct 25th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. package com.company;
  2.  
  3.  
  4. import java.io.IOException;
  5.  
  6.  
  7. import java.time.LocalTime;
  8. import java.time.format.DateTimeFormatter;
  9. import java.util.*;
  10. import java.util.stream.Collectors;
  11.  
  12. public class Main {
  13.  
  14.  
  15.     public static void main(String[] args) {
  16.         Scanner scanner = new Scanner(System.in);
  17.  
  18.         //Ако искаме да четем амтрица, която е репрезентирана от списък от списъци от Ineger,
  19.         //за да можем лесно да вадим елементи, което от масив е трудно а от List е лесно
  20.  
  21.         List<List<Integer>> matrix = readMatrix(scanner);
  22.  
  23.     }
  24.  
  25.     private static List<List<Integer>> readMatrix(Scanner scanner) {
  26.         int[] rowsAndCols = Arrays.stream(scanner.nextLine().split(" "))
  27.                 .mapToInt(Integer::parseInt)
  28.                 .toArray();
  29.  
  30.         int rows = rowsAndCols[0];
  31.         int cols = rowsAndCols[1];
  32.  
  33.         //int [][] matrix=new int[rows][cols]; тук е разликата когато искаме arrayList:
  34.  
  35.         List<List<Integer>> matrix = new ArrayList<>();
  36.  
  37.         for (int i = 0; i < rows; i++) {
  38.             // и тук е другата разлика:
  39.             // matrix[i]= Arrays.stream(scanner.nextLine().split(" "))
  40. //                    .mapToInt(Integer::parseInt)
  41. //                    .toArray();
  42.             List<Integer> list = Arrays.stream(scanner.nextLine().split(" "))
  43.                     .map(Integer::parseInt)
  44.                     .collect(Collectors.toList());
  45.             matrix.add(list);//така си четем редовете
  46.         }
  47.         return matrix;
  48.     }
  49. }
Add Comment
Please, Sign In to add comment