Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. import java.util.ArrayDeque;
  2. import java.util.Scanner;
  3.  
  4. public class L06_PrintDiagonalsOfSquareMatrix {
  5. public static void main(String[] args) {
  6. Scanner scanner = new Scanner(System.in);
  7. int[][] matrix = readMatrix(scanner);
  8. ArrayDeque<Integer> firstDiagonalQueue = new ArrayDeque<>();
  9. ArrayDeque<Integer> secondDiagonalStack = new ArrayDeque<>();
  10.  
  11. for (int i = 0; i < matrix.length; i++) {
  12. for (int j = 0; j < matrix.length; j++) {
  13. if (i == j) {
  14. firstDiagonalQueue.offer(matrix[i][j]);
  15. }
  16. if (i + j == matrix.length - 1){
  17. secondDiagonalStack.push(matrix[i][j]);
  18. }
  19. }
  20. }
  21.  
  22. while (firstDiagonalQueue.size() >= 1) {
  23. System.out.print(firstDiagonalQueue.pop() + " ");
  24. }
  25. System.out.println();
  26. while (secondDiagonalStack.size() >= 1) {
  27. System.out.print(secondDiagonalStack.poll() + " ");
  28. }
  29.  
  30. }
  31.  
  32. private static int[][] readMatrix(Scanner scanner) {
  33. int rows = Integer.parseInt(scanner.nextLine());
  34.  
  35. int[][] matrix = new int[rows][rows];
  36.  
  37. for (int row = 0; row < rows; row++) {
  38. String[] numbersToPut = scanner.nextLine().split(" ");
  39. for (int col = 0; col < rows; col++) {
  40. matrix[row][col] = Integer.parseInt(numbersToPut[col]);
  41. }
  42. }
  43. return matrix;
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement