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.

25th Jan 2019, 9:17 PM
Mike H
Mike H - avatar
3 Answers
+ 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 ()
25th Jan 2019, 11:48 PM
Denise RoƟberg
Denise RoƟberg - avatar
+ 2
Arraylist: import java.util.ArrayList; ArrayList nums = new ArrayList(); for (int i = 0; i < 10; i++){ //create randomNum nums.add (randomNum); }
26th Jan 2019, 12:02 AM
Denise RoƟberg
Denise RoƟberg - avatar
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
25th Jan 2019, 9:28 PM
Johan Besseling
Johan Besseling - avatar