0

Actually i m doing constructor implementation.But i am new to java, can any tell what going on from line 11 to 14.I am having problem in understanding the bold in line 12 and line 13.Plz help.....


1. public class Animal {
2. String name;
3. Animal(String name) {
4. this.name = name;
5. }
6.
7. Animal() {
8. this(makeRandomName());
9. }
10.
11. static String makeRandomName() {
12. int x = (int) (Math.random() * 5);
13. String name = new String[] {"Fluffy", "Fido",
"Rover", "Spike",
"Gigi"}[x];
14. return name;
15. }
16.
17. public static void main (String [] args) {
18. Animal a = new Animal();
19. System.out.println(a.name);
20. Animal b = new Animal("Zeus");
21. System.out.println(b.name);
22. }
23. }

5
Contributors
10
Replies
11
Views
7 Years
Discussion Span
Last Post by stultuske
Featured Replies
  • 1
    Ezzaral 2,714   7 Years Ago

    Well, line 12 is generating a random int from 0-5. So what effect do you think that has in line 13? Read More

  • 1

    [CODE] int x = (int) (Math.random() * 5);[/CODE] Start on the inside and work out. What does the Math.random() method return? Read the API doc The value returned is multiplied by 5 (*5) That value is then cast to an int: (int) Now read what Ezzaral asked. Slight correction for … Read More

1

Well, line 12 is generating a random int from 0-5. So what effect do you think that has in line 13?

1
int x = (int) (Math.random() * 5);

Start on the inside and work out. What does the Math.random() method return? Read the API doc
The value returned is multiplied by 5 (*5)
That value is then cast to an int: (int)

Now read what Ezzaral asked.

Slight correction for the range of values: 0-4
See the API doc about the range of values returned by random for the explanation.

Edited by NormR1: n/a

1

Math.random() produces a number where 0 <= x < 1. Therefore, Math.random()*5, produces a number where 0<=x<5. (So it will pick an index from 0 to 4.).

(int) (Math.random() * 5);

The (int) Just casts the value of the random number to type int, doing this 'cuts' off any numbers after the decimal, so you are left with a whole number.

0

> Slight correction for the range of values: 0-4

Good point. I misstated that.

We forgive you. :)

0

I got the point.But in line 13, do they assign the index x to array or something else.Thanks to all for reply.

0

in line 13, I think you'll be running into some problems:
you're declaring a regular String object, and you're trying to instantiate it as an array of String objects

0

Notice the [x] at the end.

When in doubt, copy the code into a test program and see what happens.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.