如何在 Java 中显示 N x N 随机数矩阵?
我正在尝试创建一个随机双数矩阵。矩阵的大小必须为 nxn,所有数字必须在 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 循环顶部并添加新数组...?请帮忙=(
非常感谢任何帮助。谢谢。
I'm trying to create a matrix of random double numbers. The matrix must be of size n x n and all numbers must be between 1 and 100. I've been trying to sort it out for ages now and I know it must be something so simple (as it usually is).
Here is my code:
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));
}
When I run the code I get a random array repeated n times like :
[[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]]
I think I need to go back to the top of the for loop and add the new array...? Please help =(
Any help is much appreciated. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过这样的操作:
打印图表:
用方括号打印图表:
另外,这看起来很像家庭作业,如果是的话,请像这样标记它:)
Did you try something like this:
to Print the graph:
To Print Graph with Square brackets:
Also, this seems a lot like homework, if it is, please tag it like so :)
嗨,这一切提供了我一直在寻找的答案
Hi all this provides the answer I was looking for