如何显示在Java中的N×随机数的N矩阵？

问题描述投票：2回答：2

``````public static void main(String[] args) {
PrintRandomGraph(RandomArray(4));
}

private static double[] RandomArray(int n) {
double[] randomArray = new double[n];
double[][] randomMatrix = new double [n][n];

Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {

Integer r = rand.nextInt()% 100;
randomArray[i] = Math.abs(r);
for (int j = 0; j < n; j++) {
Arrays.fill(randomMatrix, i, i+1, randomArray);
}
}

return randomArray;
}

private static void PrintRandomGraph(double[] inputArray) {
int n = inputArray.length;
double[] showArray = new double[n];
double[][] showMatrix = new double [n][n];

for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
double r = inputArray[i];
showArray[i] = r;
Arrays.fill(showMatrix, i, i+1, showArray);
}
}

System.out.println(Arrays.deepToString(showMatrix));
}
``````

[[63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0]]

java arrays matrix for-loop
2个回答
3

``````private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][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 void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(array[i][j]);
}
}
}
``````

``````public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
System.out.print(" [ ");
for (int j = 0; j < n; j++) {
System.out.print(array[i][j]);
}
//Put println instead of print here to have each row in a new line
System.out.print(" ]");
}
}
``````

0

`````` 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){

//PrintRandomGraph(RandomArray(5));
System.out.println(Arrays.deepToString(RandomArray(5)));
}
``````