First, the Math.random() method on its own generates a random number that is greater or equal to 0, but less than 1.

Obviously, decimal numbers are rather difficult to use, so we cast the result to an int.
(int)(Math.random()) will always return 0, because the method never returns anything greater than or equal to one, and casting to int doesn't round.

If the possible only result is 0, it isn't very useful. Thus, we multiply results then cast.
(int)(Math.random()*5) will produce 0, 1, 2, 3, or 4. If it returns anything less than 0.2, for example, 0.15, that multiplied by 5 is 0.75, which when cast becomes 0. If it returns, say 0.5, then after multiplying it becomes 2.5, and then after casting becomes 2.

Note: You will never get the number of which it is multiplied by, in this case 5. That's because even if it returns 0.9999, that multiplied by 5 is still less than 5, and thus after casting becomes 4.

If you don't want numbers starting at 0, then simply add the number on, but also subtract it from the high bound. Let's say you want numbers between 2 and 5.
(int)(Math.random()*5+2) can produce numbers up to 6, because if Math.random() returns 0.9999, multiplying it by 5 is around 4, and then adding 2 to it makes it 6.
Thus, the proper way to do it is (int)(Math.random()*(5-2)+2)

can I have another question??
how can I store the value of int rand in an array?
I used this code

int [] store = new int [9];
store[a] = rand;
for (int i = 0; i < 10; i++) {
System.out.print(" " + store[a]);

It only prints the last digit of int rand.

Edited
by abby2589: n/a

0

coil

Hm. It should work...are you getting any errors? Also, put a System.out.print call before you set the value of store[a] to rand, that displays the value of rand. If the value printed there and the value printed out by store[a] are the same, there's something wrong with the way you generated the number "rand".

You might want to get rid of your for-loop (unrelated), unless you actually do want to print out 10 times the value of store[a].

public class StudentListings{
private String name; // key field
private int ID;
private double GPA;
private int next;
private int size;
private StudentListing[] data;
public StudentListings(){
this.name= name;
this.id= ID;
this.gpa=GPA;
}
public StudentListings(){
next=0;
data= new StudentListings[Size];
size= Size;
} // end of constructor
...