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 trialYord Learn
1,383 PointsDeclare 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
5,205 PointsIn 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];
Gunjeet Hattar
14,483 PointsHi 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
1,383 PointsHi Gunjeet. Thank you very much for your kind help!
Yord Learn
1,383 PointsYord Learn
1,383 PointsThank you very much Kate! That solved my problem ^^