Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- //Same thing
- //More practice of functions and parameters
- public class Matrices {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- System.out.println("Enter number of rows: ");
- int numRows = in.nextInt();
- System.out.println("Enter number of columns: ");
- int numColumns = in.nextInt();
- if ((numRows > 0 && numRows < 10) && ((numColumns > 0 && numColumns < 10))) {
- if (numRows <= numColumns) {
- int[][] matrix1 = new int[numRows][numColumns];
- int[][] matrix2 = new int[numRows][numColumns];
- int[][] empty = new int[numRows][numColumns];
- for (int i = 0; i < empty.length; i++) {
- for (int j = 0; j < empty.length; j++) {
- empty[i][j] = 0;
- }
- }
- System.out.println("Elements of first matrix: ");
- for (int i = 0; i < numRows; i++) {
- for (int j = 0; j < numColumns; j++) {
- matrix1[i][j] = in.nextInt();
- }
- }
- System.out.println("Elements of second matrix");
- for (int i = 0; i < numRows; i++) {
- for (int j = 0; j < numColumns; j++) {
- matrix2[i][j] = in.nextInt();
- }
- }
- System.out.println("First matrix");
- printMatrix(matrix1);
- System.out.println("Second matrix: ");
- printMatrix(matrix2);
- System.out.println("Sum: ");
- int[][] sum = sumMatrix(matrix1, matrix2);
- printMatrix(sum);
- System.out.println("First next to the Second");
- printTwoMatrices(matrix1, matrix2);
- System.out.println("Direct: ");//as much as it may be called "direct"
- printTwoMatrices(matrix1, empty);
- printTwoMatrices(empty, matrix2);
- } else {
- System.out.println("Number of Rows less or equal to Number of Columns");
- }
- } else {
- System.out.println("Invalid!");
- }
- }
- public static void printMatrix(int[][] matrix) {
- for (int[] ints : matrix) {
- for (int column = 0; column < matrix[0].length; column++) {
- System.out.print(" " + ints[column] + " ");
- }
- System.out.println();
- }
- }
- private static int[][] sumMatrix(int[][] first, int[][] second) {
- int rows = first.length;
- int columns = first[0].length;
- int[][] sum = new int[rows][columns];
- for (int row = 0; row < rows; row++) {
- for (int column = 0; column < columns; column++) {
- sum[row][column] = first[row][column] + second[row][column];
- }
- }
- return sum;
- }
- public static void printTwoMatrices(int[][] first, int[][] second) {
- for (int i = 0; i < first.length; i++) {
- for (int j = 0; j < first[i].length; j++) {
- System.out.print(" " + first[i][j] + " ");
- }
- for (int j = 0; j < second[i].length; j++) {
- System.out.print(" " + second[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement