本文介绍了如何将所有双精度值更改为随机数?爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何将所有50个双精度变量更改为随机数?
I was wondering how do I change all 50 double variables into random numbers?
class Main {
public static void main(String[] args) {
double[] numList = new double[50];
}
}
推荐答案
Arrays#setAll
引用Javadoc:
Arrays#setAll
To quote the Javadoc:
i->Math.random()
部分提供了我们的生成器功能.
The i -> Math.random()
part is providing our generator function.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
double[] numList = new double[50];
Arrays.setAll(numList, i -> Math.random());
System.out.println(Arrays.toString(numList));
}
}
示例运行的输出:
或者,
import java.util.Arrays;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
double[] numList = IntStream.range(0, 50)
.mapToDouble(i -> Math.random()).toArray();
System.out.println(Arrays.toString(numList));
}
}
或者,
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) {
double[] array = new Random().doubles(50).toArray();
System.out.println(Arrays.toString(array));
}
}
或者,
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
double[] array = ThreadLocalRandom.current().doubles(50).toArray();
System.out.println(Arrays.toString(array));
}
}
或者,
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
final int SIZE = 50;
double[] array = new double[SIZE];
for (int i = 0; i < SIZE; i++) {
array[i] = ThreadLocalRandom.current().nextDouble();
}
System.out.println(Arrays.toString(array));
}
}
或者,
import java.util.Arrays;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Double[] array = Stream.generate(Math::random).limit(50).toArray(Double[]::new);
System.out.println(Arrays.toString(array));
}
}
或者,
import java.util.Arrays;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
double[] array = Stream.generate(Math::random).limit(50).mapToDouble(Double::valueOf).toArray();
System.out.println(Arrays.toString(array));
}
}
这篇关于如何将所有双精度值更改为随机数?爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!