Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Arrays Gotchas and Wins Array Usage in Method Declarations

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

return spots[random.nextInt(spots.lenght)];

Around 5:55 minute, lecturer is saying that method spots.lenght will not include the highest number, why? Why would we use such a method?

3 Answers

Yanuar Prakoso
Yanuar Prakoso
15,196 Points

Hi Andre...

the method random.nextInt(max number) ** basically select one random number from **0 <= random_number < max_number. Therefore in the lecture case where the spot options are: "Que Sabrosa", "Las Primas", "life of Pie" then the program will put these options into an Array called spots:

Array spots = {"Que Sabrosa", "Las Primas", "Life of Pie" }

The length of the Array spots can be calculated using spots.length which in this case the answer is 3 right. So we will use this number to produce random number using:

random.nextInt(spot.length) which means random.nextInt(3)

This will generate random integer which option will be 0, or 1, or 2. This generated random number in the code were put inside '[ ]' bracket. It means the random number will be used as index to the Array components.

But wait! isn't there are 3 spots to choose from? Yes indeed there are 3 spots but we will designate them using Array indexing. Array indexing however, starts from zero not from 1. Therefore the first spot in this case "Que Sabrosa" will be designated as spots[0], please note the number inside [] is an index of the array.

Therefore, "Las Primas" will be spot[1], and "Life of Pie" will be spot[2].

This is the answer of your second question: Why would we use such a method? well imagine if the random number generator produce number up to 3. It will result nothing from spot Array which has maximum index number of 2 because the indexing started from 0 not 1.

I hope this can help you a little. Any additional inputs are welcome since I am also still learning.

Jose Acevedo
Jose Acevedo
2,395 Points

Wasn't it ".length" instead of ".lenght"?