简体   繁体   English

如何在数组中生成随机双打?

[英]How do I generate random doubles in an Array?

My goal is to ask the user for an array length and generate a list of random doubles to fill that array out.我的目标是向用户询问数组长度并生成一个随机双精度列表来填充该数组。 I don't understand how to get Math.random into my array.我不明白如何将 Math.random 放入我的数组中。 I started with a different approach and scrapped it.我开始采用不同的方法并废弃它。 Why does double random = Math.random() * array;为什么 double random = Math.random() * array; not import a random generator into my array?不将随机生成器导入我的数组?

import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;

public class Average
{
  public static void main(String[] args)
  {
    /*Scanner in = new Scanner (System.in);

    System.out.println("Please enter your array size: ");
    int size = in.nextInt();
    int[] awnser = new int[size]; */
    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter a number");

    double[] array = new double[scanner.nextDdouble()];
    double random = Math.random() * array;
    System.out.println(array.length);

    }
  }

With your current solution you'd need to iterate with a counter starting from 0 and ending before the given size, assigning each array element with a nextDouble invocation.使用当前的解决方案,您需要使用从 0 开始并在给定大小之前结束的计数器进行迭代,并使用nextDouble调用分配每个数组元素。

Multiplying an array object by a number is just not supported in Java. Java 不支持将数组对象乘以数字。

Here's a Java-8 idiom that you may favor instead:这是一个您可能会喜欢的 Java-8 习语:

DoubleStream
    .generate(ThreadLocalRandom.current()::nextDouble)
    .limit(yourGivenSize)
    .toArray();

This will give you a double[] of size yourGivenSize , whose elements are generated randomly.这将为您提供一个double[]大小的yourGivenSize ,其元素是随机生成的。

Why does double random = Math.random() * array;为什么 double random = Math.random() * array; not import a random generator into my array?不将随机生成器导入我的数组?

You have misunderstood how this class works.你误解了这个类的工作原理。 Here is a good explanation of what this class does. 这里很好地解释了这个类的作用。 What I believe you are trying to do is something along the lines of:我相信您正在尝试做的是以下方面的事情:

    Random rand = new Random();
    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter a number");
    //create an array with the size entered by the user
    double[] array = new double[scanner.nextInt()];
    //populate the array with doubles
    for(int i =0; i < array.length; i++) {
        array[i] = rand.nextDouble();
    }

nextDouble returns a pseudorandom number between 0 and 1.0, so you'll need to multiply it by your upper bound. nextDouble返回一个介于 0 和 1.0 之间的伪随机数,因此您需要将其乘以上限。 (ie if 100 was your upper limit rand.nextDouble() * 100; ) (即,如果 100 是您的上限rand.nextDouble() * 100;

(Make sure to import theRandom class) (确保importRandom类)

Arrays#setAll

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        double[] array = new double[10];
        Arrays.setAll(array, i -> Math.random());
        System.out.println(Arrays.toString(array));
    }
}

Output of a sample run:示例运行的输出:

[0.1182317810027168, 0.9437573020895418, 0.2690105524813662, 0.6771923722130754, 0.04893586074165357, 0.42483010937765653, 0.16310798731469023, 0.2541941051963008, 0.9838342001474454, 0.8595732419001068] [0.1182317810027168,0.9437573020895418,0.2690105524813662,0.6771923722130754,0.04893586074165357,0.42483010937765653,0.16310798731469023,0.2541941051963008,0.9838342001474454,0.8595732419001068]

Alternatively,或者,

import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        double[] array = new double[10];
        
        array = IntStream.range(0, array.length)
                    .mapToDouble(i -> Math.random())
                    .toArray();
        
        System.out.println(Arrays.toString(array));
    }
}

Alternatively,或者,

import java.util.Arrays;
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        double[] array = new Random().doubles(10).toArray();
        System.out.println(Arrays.toString(array));
    }
}

Alternatively,或者,

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        double[] array = ThreadLocalRandom.current().doubles(10).toArray();
        System.out.println(Arrays.toString(array));
    }
}

Alternatively,或者,

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        final int SIZE = 10;
        double[] array = new double[SIZE];

        for (int i = 0; i < SIZE; i++) {
            array[i] = ThreadLocalRandom.current().nextDouble();
        }
        
        System.out.println(Arrays.toString(array));
    }
}

Alternatively,或者,

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(10).toArray(Double[]::new);
        System.out.println(Arrays.toString(array));
    }
}

Alternatively,或者,

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(10).mapToDouble(Double::valueOf).toArray();
        System.out.println(Arrays.toString(array));
    }
}

Java 8+ Java 8+

You can use ThreadLocalRandom with the Random#doubles method.您可以将ThreadLocalRandomRandom#doubles方法一起使用。

import java.util.concurrent.ThreadLocalRandom;
//...
double[] randoms = ThreadLocalRandom.current().doubles(10).toArray();
//Generate 10 random doubles

double[] randoms = ThreadLocalRandom.current().doubles(10, 0, 5).toArray();
//Generate 10 random doubles between 0 (inclusive) and 5 (exclusive)

I am not entirely sure what you are trying to do, what is the range of the values you are trying to get inside your array ?我不完全确定您要做什么,您要在数组中获取的值的范围是多少? In any case I think this should achieve what you are trying to do, I am using a command line argument here to supply the array length, feel free to change that back to a scanner.无论如何,我认为这应该可以实现您想要做的事情,我在这里使用命令行参数来提供数组长度,可以随意将其改回扫描仪。

int arrayLength = Integer.parseInt(args[0]);

double[] array = new double[arrayLength];
for (int i = 0; i < arrayLength; i++)
    array[i] = Math.random() * arrayLength;
System.out.println(Arrays.toString(array));

To generate random values of a specific range:要生成特定范围的随机值:

Min + (int)(Math.random() * ((Max - Min) + 1))

I used your original idea to calculate the amount of times you loop to generate your random double numbers.我用你最初的想法来计算你循环生成随机双数的次数。 As you know array index (or positions) starts at zero.如您所知,数组索引(或位置)从零开始。 So I used a for loop to begin at zero and once the number is generated this line: list[i] = num;所以我使用了一个 for 循环从零开始,一旦生成了这一行:list[i] = num; places the random number into the first index(position) of the array and continues until it reaches the size the user specified.将随机数放入数组的第一个索引(位置)并继续直到达到用户指定的大小。

package stack;

    import java.util.Scanner;
    import java.util.Random;

    public class Stack {

    public static void main(String[] args){

      Scanner input = new Scanner(System.in);
      System.out.println("enter a number");

    int size = input.nextInt();
       Double[] list = new Double[size];

       for(int i = 0; i < size; i++){
            Double num = Math.random();
            list[i] = num;
       }
     System.out.println(list.length);
    }
    }

/*  for(int i = 0; i< list.length; i++){
     System.out.println(list[i]);  }
*/

I also included if you want to check the array contents.如果您想检查数组内容,我还包括在内。 I created another for loop with the same concept as the first loop by checking each index(position) and display them.我通过检查每个索引(位置)并显示它们,创建了另一个与第一个循环具有相同概念的 for 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM