Я самостоятельно изучаю Java и застрял в создании 2D-массива, который инициализирует его случайными значениями, а затем создает транспонирование массива.
Пример вывода:
$ 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`
^ Должен быть конечный результат. Будем признательны за помощь с кодом!
Я хотел бы создать код для генерации сообщений об ошибках, если количество строк или столбцов выходит за пределы указанного диапазона. А если читать элементы матрицы из командной строки, а не генерировать их случайным образом.
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...
}
}
Подробнее здесь: https://stackoverflow.com/questions/261 ... a-2d-array