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

How do I get the index value of the lowest value element in an Array?

I am using Android Studio.

I have a database of cities, Of which when a user enters a city,

The application gets a list of cities with that name. The application then creates an array of the latitudes and longitudes of all those cities.

for (int i = 0; i < citylist.size(); i++) {

                        ParseObject city = citylist.get(i);
                        Number citylat = city.getNumber("lat");
                        Number citylng = city.getNumber("lng");

                        mLatArray[i] = (Double) citylat;
                        mLngArray[i] = (Double) citylng;

                        mClosestLatArray[i] = mLatitude - mLatArray[i];
                        mClosestLatArray[i] = Math.abs(mClosestLatArray[i]);
                        mClosestLongArray[i] = mLongitude - mLngArray[i];
                        mClosestLongArray[i] = Math.abs(mClosestLongArray[i]);
                        mClosestCoordsArray[i] = mClosestLatArray[i] + mClosestLongArray[i];
                    }

I then want to get the index value of the lowest element in mClosestCoordsArray.

I don't know how? Can I do so on Android?

I know its a simple matter in Java, but idk how to do it here.

1 Answer

If you know how to do it in Java, you already have the answer! Android source files are written in Java. Add the array search code to a method and you're done! As a reminder, the simplest solution is:

double min = mClosestCoordsArray[0];
for (int i = 1; i < mClosestCoordsArray.length; i++) {
    if (mClosestCoordsArray[i] < min) {
        min = mClosestCoordsArray[i];
    }
}