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

Dawson Forbes
Dawson Forbes
487 Points

I always get: Bummer! java.lang.ArrayIndexOutOfBoundsException: 3 ()

I only get it in that task part and I've tried doing:

String lastSport = sports[3]; & String lastSport = sports[numberOfSports];

Both of them give them same error

Array.java
String[] sports = { "Basketball", "Baseball", "Tennis"};
String bestSport = sports[0];
int numberOfSports = sports.length;
String lastSport = sports[sports.length];

hi Dawson,

To get the last sport value from the array, you will need:

String lastSport = sports[sports.length - 1];

or

String lastSport = sports[numberOfSports - 1];

This is because arrays are zero indexed. This means that the first value is at index 0 and the last one is at 2.

cheers, Swap

1 Answer

Hao Tran
Hao Tran
17,264 Points

You've shown that you understand that arrays are 0-indexed (aka the first element has an index of 0). The length of the array is indeed 3, but because it's 0-indexed, if you write sports[3], you're actually asking for the FOURTH element in the array. To get the last (third) element, you want to use index 2.

String lastSport = sports[sports.length - 1];

Of course, you could replace the index with "numberOfSports - 1" or similar.