Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Simple Android App (2014) Coding the Fun Facts Using an Array

how do i do it

how to do this challenge

String[] sports = { "Basketball", "Baseball", "Tennis" };

if (randomNumber == 0) {
  fact = "Basketball";

2 Answers

Hi Steve,

I'll walk you through this. You start with the following code:

String[] sports = { "Basketball", "Baseball", "Tennis" };

Which is a string array holding three strings. The first task is Declare a String variable named bestSport and initialize it to the first element of the sports array.

So, we start with declaring a string variable and naming it:

String bestSport = 

We want to initialise it with the first element of the array that we've been given. Array elements start counting at zero, so the first element is [0]. Finishing that task, therefore, gives:

String bestSport = sports[0];

The next task is Declare an int variable named numberOfSports and set it to the number of elements in the array using the array's length property. That looks like:

int numberOfSports = sports.length;

And the last challenge is Declare a String variable named lastSport and initialize it with the last element of the sports array. There's a couple of ways of doing that. We can just say:

String lastSport = sports[2];

Because we know how long the array is - we can see the three elements so can say the last element is 0, 1, 2. However, that's hardcoding the result. What if more sports get added to the array later? We'll still be using sports[2] which would then be wrong!

In the previous task, we obtained the length of the array. We can use that, right? We know that the length of the array gives the number of elements in the array but those elements start being counted from zero in the code. So, the array has three elements, its last element is sports[2].

So if we wrote:

String lastSport = sports[numberOfSports - 1];

That would use the integer we created in the previous challenge to access the last element of the array without hard-coding the result.

Make sense?


thank you