问题描述
我需要使用构造函数创建一个数组,添加一个将数组打印为序列的方法和一个用 double 类型的随机数填充数组的方法.
I need to create an array using a constructor, add a method to print the array as a sequence and a method to fill the array with random numbers of the type double.
这是我到目前为止所做的:
Here's what I've done so far:
import java.util.Random;
public class NumberList {
private static double[] anArray;
public static double[] list() {
return new double[10];
}
public static void print(){
System.out.println(String.join(" ", anArray);
}
public static double randomFill() {
return (new Random()).nextInt();
}
public static void main(String args[]) {
// TODO
}
}
我正在努力弄清楚如何用我在 randomFill 方法中生成的随机数填充数组.谢谢!
I'm struggling to figure out how to fill the array with the random numbers I have generated in the randomFill method. Thanks!
推荐答案
您需要添加逻辑以使用 randomFill 方法将随机值分配给 double[] 数组.
You need to add logic to assign random values to double[] array using randomFill method.
改变
public static double[] list(){
anArray = new double[10];
return anArray;
}
到
public static double[] list() {
anArray = new double[10];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray;
}
然后就可以调用main方法中的list()和print()等方法来生成随机的double值并在控制台打印double[]数组.
Then you can call methods, including list() and print() in main method to generate random double values and print the double[] array in console.
public static void main(String args[]) {
list();
print();
}
一个结果如下:
-2.89783865E8
1.605018025E9
-1.55668528E9
-1.589135498E9
-6.33159518E8
-1.038278095E9
-4.2632203E8
1.310182951E9
1.350639892E9
6.7543543E7
这篇关于用随机数填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!