Fill an array with random numbers

后端 未结 13 2286
感动是毒
感动是毒 2020-12-03 11:54

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.

He

13条回答
  •  醉话见心
    2020-12-03 12:19

    You can simply solve it with a 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.

提交回复
热议问题