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

Java Java Data Structures - Retired Efficiency! Implement Chooser UI

Sean M
Sean M
7,344 Points

Java: Implement the chooser ui

private int promptForIndex(List<String> options) throws IOException {
        int counter = 1;
        for(String option: options) {
            System.out.println("%d.) %s %n", counter, option);
            counter++;
        }
        String optionAsString = mReader.readLine();
        int choice = Integer.parseInt(optionAsString.trim());
        System.out.println("Your choice:  ");
        return choice: -1;
    }

I just wanted to know a little bit more of what this function is doing. Specifically, the purpose of the IOException, counter, and trim.

Thanks for the feedback.

Moderator edited: Slight correction of markdown.

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Sean M! I took the liberty of slightly correcting your markdown.

As for your question, the IOException is thrown when something unexpected happens to the stream that is being read in. It could be any number of things. You could have the network die when reading in something over a network connection. Maybe it can't find the file. There are many different things that can happen to the stream that might cause it to return a null. This is here to throw that error when this happens. You might check the documentation.

The counter variable is used for formatting and letting the user know that they can pick a song by its number instead of typing the song name. We start it at one because that's how most humans count. You can see the results of this around 16:59 of the video. On the screen you should see:

1). Michael Jackson

That one is the counter.

Finally, the trim method is used to trim any remaining whitespace from around what the user types in. This was covered around 2:42 of the video.

Hope this helps! :sparkles:

Sean M
Sean M
7,344 Points

I appreciate the quick repose Jennifer.

I've understood these concepts in previous material, I just needed some clarification for this example.

Thanks a lot.