Advertisement
vaakata

Ex08_MatroxShuffling_21Jan2017

Jan 21st, 2017
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.29 KB | None | 0 0
  1. import java.util.Locale;
  2. import java.util.Scanner;
  3. public class Ex08_MatrixShuffling_21Jan2017 {
  4.     public static void main(String[] args){
  5.         Locale.setDefault(Locale.ROOT);
  6.         Scanner scan = new Scanner(System.in);
  7.         String[] matrixSize = scan.nextLine().split("\\s");
  8.         int rows = Integer.parseInt(matrixSize[0]);
  9.         int cols = Integer.parseInt(matrixSize[1]);
  10.         boolean stopCommandsTaking = false;
  11.        
  12.         String[][] matrix = fillTheMatrix(scan, rows, cols);
  13.  
  14.         do {
  15.             String[] commands = scan.nextLine().split("\\s");
  16.             if(commands[0].equals("swap")){
  17.                 try {
  18.                     matrix = swapItems(commands, matrix);
  19.                     //Print current matrix condition
  20.                     for (String[] row : matrix) {
  21.                         for (String item : row) {
  22.                             System.out.print(item + " ");
  23.                         }
  24.                         System.out.println();
  25.                     }
  26.                 } catch (ArrayIndexOutOfBoundsException ex) {
  27.                     System.out.println("Invalid input!");
  28.                 }
  29.             } else if(commands[0].equals("END")){
  30.                 stopCommandsTaking = true;
  31.             } else {
  32.                 System.out.println("Invalid input!");
  33.             }
  34.         } while(stopCommandsTaking == false);
  35.     }
  36.  
  37.     private static String[][] swapItems(String[] commands, String[][] matrix) {
  38.         String[][] swapMatrix = matrix;
  39.         String temp = matrix[Integer.parseInt(commands[1])][Integer.parseInt(commands[2])];
  40.         swapMatrix[Integer.parseInt(commands[1])][Integer.parseInt(commands[2])] = swapMatrix[Integer.parseInt(commands[3])][Integer.parseInt(commands[4])];
  41.         swapMatrix[Integer.parseInt(commands[3])][Integer.parseInt(commands[4])] = temp;
  42.         return swapMatrix;
  43.     }
  44.  
  45.     private static String[][] fillTheMatrix(Scanner scan, int rows, int cols) {
  46.         String[][] inputMatrix = new String[rows][cols];
  47.         for (int row = 0; row < rows; row++) {
  48.             String[] currentRow = scan.nextLine().split("\\s");
  49.             for (int col = 0; col < cols; col++) {
  50.                 inputMatrix[row][col] = currentRow[col];
  51.             }
  52.         }
  53.         return inputMatrix;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement