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.
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 ()
+ 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