Kotlinlearncs.online LogoJava
Return to List

Homework: Script Parser

Created By: Geoffrey Challen
/ Version: 2022.2.0

Write a method called parseScript that accepts a single String and returns a Map<String, List<String>>. The passed String contains a script consisting of lines separated by newlines, each with the following format:

Name: Line

For example, here's a simple script:

Geoffrey: What do you think of this homework problem?
Ahmed: it's a bit sus
Geoffrey: I bet they'll be able to figure it out!
Maaheen: We'll be here to help if they need it.

parseScript parses the script and returns a map mapping each character's name to their lines in order. So, for the script above, the map would contain three keys: "Geoffrey", "Ahmed", and "Maaheen". The List<String> for the key "Geoffrey" would contain the Strings "What do you think of this homework problem!" and "I bet they'll be able to figure it out!" The List<String> for the key "Amhed" would contain the String "it's a bit sus".

A few hints for approaching this problem.

You'll want to use .split to parse the passed String into individual lines. You should assert that the passed String is not null, but if it's not, it will have the format described above, and also not contain any blank lines.

You'll also need to use .split to split each line into the name and their line of dialog. You can assume that the character ":" only appears to delimit the name of the rest of the line.

The first time you encounter a character, there will not be an entry in your map for them. So you should check for this, and create the ArrayList when appropriate.

There may be extra whitespace around the name or the line of dialogue, so use .trim appropriately.

The following imports are provided for you: java.util.List, java.util.ArrayList, java.util.Map, and java.util.HashMap. You should not need to use other imports to solve this problem.

Related Lessons

Stuck? You may find these lessons helpful: