I'm self teaching myself some java and I'm stuck on creating a 2D array that initializes it with random values and then creates the transpose of the array.
An example output is:
$ java Test1 22 333 44 555 6
Enter the number of rows (1-10): 0
ERROR: number not in specified range (1-10) !
and so on until you enter the correct number of rows and columns.
1 22 333 44 555 6
1 333 555` 22 44 6`
^ Should be the final output. Some help with the code would appreciated!
I would like to code to generate error messages if the number of rows or columns is outside the specified range. And for if to read the matrix elements from the command line and not generate them randomly.
import java.util.Scanner;
public class Test1 {
/** Main method */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows (1-10): ");
int rows = input.nextInt();
System.out.print("Enter the number of columns (1-10): ");
int cols = input.nextInt();
// Create originalMatrix as rectangular two dimensional array
int[][] originalMatrix = new int[rows][cols];
// Assign random values to originalMatrix
for (int row = 0; row < originalMatrix.length; row++)
for (int col = 0; col < originalMatrix[row].length; col++) {
originalMatrix[row][col] = (int) (Math.random() * 1000);
}
// Print original matrix
System.out.println("\nOriginal matrix:");
printMatrix(originalMatrix);
// Transpose matrix
int[][] resultMatrix = transposeMatrix(originalMatrix);
// Print transposed matrix
System.out.println("\nTransposed matrix:");
printMatrix(resultMatrix);
}
/** The method for printing the contents of a matrix */
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
/** The method for transposing a matrix */
public static int[][] transposeMatrix(int[][] matrix) {
// Code goes here...
}
}
This is a simple method that return an int[][] of the transposed matrix...
public static int[][] transposeMatrix(int[][] matrix){
int m = matrix.length;
int n = matrix[0].length;
int[][] transposedMatrix = new int[n][m];
for(int x = 0; x < n; x++) {
for(int y = 0; y < m; y++) {
transposedMatrix[x][y] = matrix[y][x];
}
}
return transposedMatrix;
}
Than to print a 2D matrix you can use a method like this:
public static String matrixToString(int[][] a){
int m = a.length;
int n = a[0].length;
String tmp = "";
for(int y = 0; y<m; y++){
for(int x = 0; x<n; x++){
tmp = tmp + a[y][x] + " ";
}
tmp = tmp + "\n";
}
return tmp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With