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 trialsteve apgar
Courses Plus Student 568 Pointshow do i do it
how to do this challenge
String[] sports = { "Basketball", "Baseball", "Tennis" };
if (randomNumber == 0) {
fact = "Basketball";
}
2 Answers
Steve Hunter
57,712 PointsHi 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?
Steve.
steve apgar
Courses Plus Student 568 Pointsthank you