gpt4 book ai didi

java - 创建随机数组方法

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:40 24 4
gpt4 key购买 nike

我有以下代码:

import java.util.*;

public class Lab7 {

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub

double[][] g = { { 0, 1, 2 }, { 1, 0, 3 }, { 2, 3, 0 } };
double mst[][] = MST.PrimsMST(g);
PrintArray(g);
PrintMST(mst);
}

public static void PrintArray(double[][] g) {

System.out.println(Arrays.deepToString(g));

}

public static void PrintMST(double[][] mst) {

System.out.println(Arrays.deepToString(mst));

}

}

我确实需要帮助添加一个 RandomArray 方法,该方法将为我创建一个随机数组 (g),而不是我必须自己输入多维数组的值。

这是我之前用来创建随机数组的一段代码:

我似乎无法修改它以在上面的代码中使用,有人可以帮助我吗?

public static ArrayList<Integer> RandomArray(int n)   {                 // Method called RandomArray which takes a     parameter as an integer  
ArrayList<Integer> randomArray = new ArrayList<Integer>(n); // Creates an ArrayList called randomArray, of size 'n'
Random randNumGenerator = new Random(); // Creates a random object
for (int i = 0; i < n; i++){ // Creates a for loop which goes from i=0 to 'n'
randomArray.add(new Integer(randNumGenerator.nextInt(256))); // Will add a random int from 0 to 255, in the array 'randomArray'
}
return randomArray; // Returns randomArray
}

最佳答案

更改了方法以满足您的需求:

public static double[] randomArray(int n) {
double[] randomArray = new double[n];
Random randNumGenerator = new Random();
for (int i = 0; i < n; i++) {
randomArray[i] = randNumGenerator.nextDouble() * 256;
}
return randomArray;
}

现在你可以这样调用它

double[][] g = {randomArray(3), randomArray(3), randomArray(3)};

关于java - 创建随机数组方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13518448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com