wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes random method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "random method" Watch "random method" New topic
Author

random method

Venkat Ramsimha
Ranch Hand

Joined: Dec 28, 2004
Posts: 127
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

Joined: Apr 01, 2005
Posts: 431
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.


SCJP 1.4, SCWCD 1.4, SCBCD 1.3, NEXT--->IBM XML
Raghu Shree
Ranch Hand

Joined: Mar 18, 2005
Posts: 143
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.


Raghu J<br />SCJP 1.4<br /> <br />The Wind and waters are always<br />on the side of the ablest navigators.<br /><a href="http://groups.yahoo.com/group/scjp_share" target="_blank" rel="nofollow">SCJP Group</a><br /><a href="http://groups.yahoo.com/group/JavaBeat_SCWCD" target="_blank" rel="nofollow">SCWCD Group</a>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: random method
 
Similar Threads
Super class constructor
what is calling code?
can anyone explain this program
a static method call in a constructor?
instance methods