我有以下代码:
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
}
答案 0 :(得分:1)
更改了您的方法以满足您的需求:
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)};