Java 用随机数填充数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20380991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:31:38  来源:igfitidea点击:

Fill an array with random numbers

javaarrays

提问by JaAnTr

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.

我需要使用构造函数创建一个数组,添加一个将数组打印为序列的方法和一个用 double 类型的随机数填充数组的方法。

Here's what I've done so far:

这是我到目前为止所做的:

import java.util.Random;


public class NumberList {


    private static double[] anArray;

    public static double[] list(){
        anArray = new double[10];   
        return anArray;
    }

    public static void print(){
        for(double n: anArray){
        System.out.println(n+" ");
        }
    }


    public static double randomFill(){

    Random rand = new Random();
    int randomNum = rand.nextInt();
    return randomNum;
    }

    public static void main(String args[]) {

    }


}

I'm struggling to figure out how to fill the array with the random numbers i've generated in the randomFill method. Thanks!

我正在努力弄清楚如何用我在 randomFill 方法中生成的随机数填充数组。谢谢!

采纳答案by MouseLearnJava

You need to add logic to assign random values to double[] array using randomFillmethod.

您需要添加逻辑以使用randomFill方法将随机值分配给 double[] 数组。

Change

改变

 public static double[] list(){
    anArray = new double[10];   
    return anArray;
 }

To

 public static double[] list() {
    anArray = new double[10];
    for(int i=0;i<anArray.length;i++)
    {
        anArray[i] = randomFill();
    }
    return anArray;
}

Then you can call methods, including list() and print() in main method to generate random double values and print the double[] array in console.

然后你可以调用方法,包括 main 方法中的 list() 和 print() 来生成随机 double 值并在控制台中打印 double[] 数组。

 public static void main(String args[]) {

list();
print();
 }

One result is as follows:

一种结果如下:

-2.89783865E8 
1.605018025E9 
-1.55668528E9 
-1.589135498E9 
-6.33159518E8 
-1.038278095E9 
-4.2632203E8 
1.310182951E9 
1.350639892E9 
6.7543543E7 

回答by hawks

try this:

尝试这个:

public void double randomFill(){

  Random rand = new Random();
  for(int i = 0; i < this.anArray.length(); i++){
    this.anArray[i] = rand.nextInt();
  }
}

回答by SudoRahul

You can call the randomFill()method in a loop and fill your array in the main()method like this.

您可以randomFill()在循环中调用该方法并main()像这样在该方法中填充数组。

public static void main(String args[]) {
    for(int i=0;i<anArray.length;i++){
        anArray[i] = randomFill();
    }
}

Though you need to use rand.nextDouble()in the randomFill()as you seem to be having a doublearray to fill.

尽管您需要使用rand.nextDouble()in ,randomFill()因为您似乎double要填充一个数组。

double randomNum = rand.nextDouble();
return randomNum;

回答by Vivin Paliath

This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!

这看起来有点像家庭作业。所以我会给你一些提示。好消息是你快到了!你已经完成了大部分的艰苦工作!

  • Think about a construct that can help you iterateover the array. Is there some sort of construct (a loopperhaps?) that you can use to iterate over each location in the array?
  • Within this construct, for each iteration of the loop, you will assign the value returned by randomFill()to the current location of the array.
  • 考虑一个可以帮助您迭代数组的构造。是否有某种构造(也许是循环?)可用于迭代数组中的每个位置?
  • 在此构造中,对于循环的每次迭代,您会将 返回的值分配给randomFill()数组的当前位置。

Note:Your array is double, but you are returning ints from randomFill. So there's something you need to fix there.

注意:您的数组是double,但您正在int从返回s randomFill。所以你需要在那里修复一些东西。

回答by jarz

You could loop through the array and in each iteration call the randomFill method. Check it out:

您可以遍历数组并在每次迭代中调用 randomFill 方法。一探究竟:

import java.util.Random;

public class NumberList {


    private static double[] anArray;

    public static double[] list(){
        anArray = new double[10];   
        return anArray;
    }

    public static void print(){
        for(double n: anArray){
            System.out.println(n+" ");
        }
    }


    public static double randomFill(){
        Random rand = new Random();
        int randomNum = rand.nextInt();
        return randomNum;
    }

    public static void main(String args[]) {
        list();
        for(int i = 0; i < anArray.length; i++){
            anArray[i] = randomFill();
        }
        print();
    }


}

回答by MouseLearnJava

You can simply solve it with a for-loop

你可以简单地用一个 for-loop

private static double[] anArray;

public static void main(String args[]) {
    anArray = new double[10]; // create the Array with 10 slots
    Random rand = new Random(); // create a local variable for Random
    for (int i = 0; i < 10; i++) // create a loop that executes 10 times
    {
        anArray[i] = rand.nextInt(); // each execution through the loop
                                        // generates a new random number and
                                        // stores it in the array at the
                                        // position i of the for-loop
    }
    printArray(); // print the result
}

private static void printArray() {
    for (int i = 0; i < 10; i++) {
        System.out.println(anArray[i]);
    }
}

Next time, please use the search of this site, because this is a very common question on this site, and you can find a lot of solutions on google as well.

下次请使用本站搜索,因为这是本站非常常见的问题,在google上也能找到很多解决方法。

回答by Vibhatha Abeykoon

If the randomness is controlled like this there can always generate any number of data points of a given range. If the random method in java is only used, we cannot guarantee that all the numbers will be unique.

如果像这样控制随机性,则总是可以生成给定范围内的任意数量的数据点。如果只使用java中的random方法,我们不能保证所有的数字都是唯一的。

package edu.iu.common;

import java.util.ArrayList;
import java.util.Random;

public class RandomCentroidLocator {

public static void main(String [] args){
 
 int min =0;
 int max = 10;
 int numCentroids = 10;
 ArrayList<Integer> values = randomCentroids(min, max, numCentroids); 
 for(Integer i : values){
  System.out.print(i+" ");
 }
 
}

private static boolean unique(ArrayList<Integer> arr, int num, int numCentroids) {

 boolean status = true;
 int count=0;
 for(Integer i : arr){
  if(i==num){
   count++;
  }
 }
 if(count==1){
  status = true;
 }else if(count>1){
  status =false;
 }
 

 return status;
}

// generate random centroid Ids -> these Ids can be used to retrieve data
// from the data Points generated
// simply we are picking up random items from the data points
// in this case all the random numbers are unique
// it provides the necessary number of unique and random centroids
private static ArrayList<Integer> randomCentroids(int min, int max, int numCentroids) {

 Random random = new Random();
 ArrayList<Integer> values = new ArrayList<Integer>();
 int num = -1;
 int count = 0;
 do {
  num = random.nextInt(max - min + 1) + min;
  values.add(num);
  int index =values.size()-1;
  if(unique(values, num, numCentroids)){    
   count++;
  }else{
   values.remove(index);
  }
  
 } while (!( count == numCentroids));

 return values;

}

}

回答by Steven Hollinger

This will give you an array with 50 random numbers and display the smallest number in the array. I did it for an assignment in my programming class.

这将为您提供一个包含 50 个随机数的数组并显示数组中的最小数字。我是为了我编程课上的一个作业而做的。

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

    int i;
    int[] array = new int[50];
    for(i = 0; i <  array.length; i++) {
        array[i] = (int)(Math.random() * 100);
        System.out.print(array[i] + "  ");

        int smallest = array[0];

        for (i=1; i<array.length; i++)
        {
        if (array[i]<smallest)
        smallest = array[i];
        }



    }

}

}`

}`

回答by Samir Ouldsaadi

You can use IntStream ints()or DoubleStream doubles()available as of java 8 in Random class. something like this will work, depends if you want double or ints etc.

您可以在 Random 类中使用从 java 8 开始可用的IntStream ints()或 DoubleStream doubles()。像这样的东西会起作用,取决于你是想要双精度还是整数等。

Random random = new Random();

int[] array = random.ints(100000, 10,100000).toArray();

you can print the array and you'll get 100000 random integers.

你可以打印数组,你会得到 100000 个随机整数。

回答by Jeff smith

Probably the cleanest way to do it in Java 8:

可能是 Java 8 中最简洁的方法:

private int[] randomIntArray() {
   Random rand = new Random();
   return IntStream.range(0, 23).map(i -> rand.nextInt()).toArray();
}