我用随机双数创建了一个 5x5 矩阵。我需要帮助来输出每行和每列的最大元素(数字)。它将在单独的行上输出它,例如“行中最大的元素是:[x, x ,x ,x,x] ,列中的元素也是如此。
我尝试创建两个单独的方法,但尝试调用它们不起作用。
public class HomeworkOne {
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double[n][n];
double[] randomArray = new double[n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt() % 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
public static void main(String[] args) {
double[][] matrix = RandomArray(5);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(matrix[i][j]);
}
System.out.println("");
}
}
}
我还不断将矩阵中的数字压缩,因为数字之间没有空格。我怎样才能将它们格式化为每个数字之间有一个空格?
最佳答案
您可以循环遍历列和行并找到最大值; maxRow 和 maxCol 都保存最大值,两者都从索引零开始(这样您就知道最大值来自哪一行和哪列)。
double[] maxRow = new double[5];
double[] maxCol = new double[5];
double[] row = new double[5];
double[] col = new double[5];
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
row[y] = matrix[x][y];
col[y] = matrix[y][x];
}
Arrays.sort(row, 0, 4);
Arrays.sort(col, 0, 4);
maxRow[x] = row[4];
maxCol[x] = col[4];
}
I also keep getting the numbers in the matrix crunched up as in their is no space between the numbers. How could I format them to have a space between each number?
System.out.print(matrix[i][j] + " ");
关于java - 如何实现一种方法来查找 5x5 矩阵中每行和每列的最大元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57298413/