"Python Basics (Retired)" was retired on January 7, 2016.

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

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

Yord Learn
Yord Learn
1,383 Points

Declare a String variable named lastSport and initialize it with the last element of the sports array.

Does not work using: String bestSport = ""; String[] sports = { bestSport, "Basketball", "Baseball", "Tennis" }; int numberOfSports = sports.length; String lastSport = sports[numberOfSports];

2 Answers

Kate Hoferkamp
Kate Hoferkamp
5,205 Points

In your code, the number stored in numberOfSports is 4 (bestSport, basketball, baseball, & tennis). If you did sports[numberOfSports] you would be calling the sports[4] which is nonexistant because there is no 5th spot in the array.

Therefor you have to do: sports[numberOfSports - 1];

String[] sports = { "Basketball", "Baseball", "Tennis" };
String bestSport = sports[0];
int numberOfSports = sports.length;
String lastSport = sports[sports.length - 1];
Yord Learn
Yord Learn
1,383 Points

Thank you very much Kate! That solved my problem ^^

Hi Yord,

Kate has given a good answer. By convention this is the right way. However as it's evident from the question, there are only three values for the array. So you could have also written

String lastSport = sports[2];   // where 2 is the index of the last element

Hope it helps.

Yord Learn
Yord Learn
1,383 Points

Hi Gunjeet. Thank you very much for your kind help!