我正在尝试创建一个随机双数组矩阵。矩阵必须是n x n的大小,并且所有数字必须在1到100之间。我一直在努力将它排序多年,我知道它必须是如此简单的东西(通常是这样)。
这是我的代码:
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));
}
当我运行代码时,我得到一个随机数组重复n次,如:
[[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]]
我想我需要回到for循环的顶部并添加新数组......?请帮忙=(
非常感谢任何帮助。谢谢。
答案 0 :(得分: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(" ]");
}
}
另外,这看起来很像家庭作业,如果是的话,请像这样标记:)
答案 1 :(得分: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)));
}