Java - create an Array and ArrayList | Sololearn: Learn to code for FREE!

0

Java - create an Array and ArrayList

Hi I’m pretty new to java and I’m still learning. How can I create an array of 10 random Rational numbers (ex:between 1 to 50) and create an ArrayList containing the 10 Rational numbers.

1/25/2019 9:17:14 PM

Mike H

3 Answers

New Answer

+2

There are different methods to create a random number. (Google java random) Normally I use this: import java.util.Random; Random r = new Random (); int randomNum = r.nextInt (50) + 1; //creates a number between 1 - 50 To create an Array: int [] num = new int [10]; Fill the array with a loop: for (int i = 0; i < num.length; i++){ randomNum = r.nextInt (50) + 1; num [i] = randomNum; } edit: I didn't see that you want rational numbers --> double or float double num = r.nextDouble should work or use Math.random ()

+2

Arraylist: import java.util.ArrayList; ArrayList nums = new ArrayList(); for (int i = 0; i < 10; i++){ //create randomNum nums.add (randomNum); }

0

Hi, Have a look at the Java standard library. You can find documentation of both generating random numbers and creating ArrayLists :) good luck! //Johan