• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

random method

 
Venkat Ramsimha
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Animal
{
String name;
Animal(String name)
{
this.name = name;
}
Animal()
{
this(makeRandomName());
}
static String makeRandomName()
{
int x = (int) (Math.random() * 5);
String name = new String[] {"Fluffy", "Fido","Rover", "Spike","Gigi"}[x];
return name;
}
public static void main (String [] args)
{
Animal a = new Animal();
System.out.println(a.name);
Animal b = new Animal("Zeus");
System.out.println(b.name);
}
}

Hi All,
can anybody explain the random method for the above program


thanks
venkat
 
S.L.Narayanan
Ranch Hand
Posts: 431
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While creating an object for the Animal class, if u call the 1-arg constructor which takes the name of the animal then that name will be assigned as the created Animal's (object's) name.

But if u call the no-arg constructor they are selecting a name from a list of 5 names (String[]). They are creating a string with 5 elements and getting one of the elements randomly. To get the random number between 0 and 4 they are using the Math.random() function.

This function will return a value above 0.00 and less than or equal to 0.99. So what ever you get if u multiply by 5 you will get values from 0.05 to 4.95. Since they are casting it with (int) it will truncate the fractional part.

So finally you will get x value as 0<=x>=4. Since they are using x as the index to get the array element, you will get one of the 5 eleemnts from the String array as the name of the animal.
 
Raghu Shree
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String name = new String[] {"Fluffy", "Fido","Rover", "Spike","Gigi"}[x]; This line is equalent to
String []nameArray = new String[] {"Fluffy", "Fido","Rover", "Spike","Gigi"};
String name= nameArray[x];


Method makeRandom() retrieve a animal name from array name. [bold]this(name)[/bold] overload the Animal(String name) constructor and prints the animal name.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic