Java Java Data Structures Efficiency! Implement Chooser UI

Sean M
Sean M
7,339 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);
        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
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,339 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.