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

Stuck on android code challenge

Hi i'm stuck on this

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

String[] sports = { "Basketball", "Baseball", "Tennis" };
String bestSport = sports[0];
int numberOfSports = (sports.length);

1 Answer

Hi Phil,

From the code provided and have had looked at the challenge this is what you would need to do

Declare a string variable called lastSport and then assign it to the last or 3rd element (index 2) of the array i.e.

String lastSport = sports[2]; //since index 2 or element no 3 or Tennis is the last sport in the array

This should have been easy since you have already defined the first sport in the array with index [0]

Alternatively a second better way to do this challenge

String[] sports = { "Basketball", "Baseball", "Tennis" };
String bestSport = sports[0];
// int numberOfSports = (sports.length);    ... No need to put sports.length in brackets
int numberOfSports = sports.length;
String lastSport = sports[numberOfSports-1];

Reason : sports.length will give the value 3 since there are three elements. This value is now stored within numberOfSports

Now since index numbers start from 0 so the last value in an array will by convention be length of array - 1

Array

Hope this explains. Ask again if it doesn't