CSE 142, Autumn 2021: Assessment 6

Assessment 6: MadLibs

Initial submission due Tuesday, November 16 Wednesday, November 17, 11:59:59pm

Objectives

This assignment will assess your mastery of the following objectives:

  • Write a functionally correct Java program to produce specified console output.
  • Use Scanner and File to read input from a file.
  • Use PrintStream and File to write output to a file.
  • Write and call methods that accept parameters and return values to manage information flow and add structure to programs.
  • Follow prescribed conventions for spacing, indentation, naming, and comments.

Program Behavior

Make sure that the format and structure of your output exactly match the given logs.

"Mad Libs" are short stories that have blanks called placeholders to be filled in. In the non-computerized version of this game, one person asks a second person to fill in each of the placeholders without the second person knowing the overall story. Once all placeholders are filled in, the second person is shown the resulting story, often with a humorous outcome.

In this assignment you present a menu to the user with three options: create a new mad lib, view a previously created mad lib, or quit. These are represented as C, V, and Q, case-insensitively. If anything else is typed, the user is re-prompted.

Menu options should be case-insensitive. If an unrecognized option is entered, the user should be re-prompted until a valid option is given.

When creating a new mad lib, the program prompts the user for input and output file names. Then the program reads the input file, prompting the user to fill in any placeholders that are found without showing the user the rest of the story. As the user fills in each placeholder, the program writes the resulting text to the output file. The user can later view the mad lib that was created or quit the program. The log below shows one sample execution of the program:

Sample program execution #1
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.

(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: oops.txt
File not found. Try again: TORZON.txt
File not found. Try again: tarzan.txt
Output file name: out1.txt

Please type an adjective: silly
Please type a plural noun: apples
Please type a noun: frisbee
Please type an adjective: hungry
Please type a place: Tacoma, WA
Please type a plural noun: bees
Please type a noun: umbrella
Please type a funny noise: burp
Please type an adjective: shiny
Please type a noun: jelly donut
Please type an adjective: beautiful
Please type a plural noun: spoons
Please type a person's name: Keanu Reeves
Your mad-lib has been created!

(C)reate mad-lib, (V)iew mad-lib, (Q)uit? X
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? I don't understand.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? V
Input file name: OUT001.txt
File not found. Try again: i forget the file name
File not found. Try again: something.DOC
File not found. Try again: out1.txt

One of the most silly characters in fiction is named
"Tarzan of the apples ." Tarzan was raised by a/an
frisbee and lives in the hungry jungle in the
heart of darkest Tacoma, WA . He spends most of his time
eating bees and swinging from tree to umbrella .
Whenever he gets angry, he beats on his chest and says,
" burp !" This is his war cry. Tarzan always dresses in
shiny shorts made from the skin of a/an jelly donut
and his best friend is a/an beautiful chimpanzee named
Cheetah. He is supposed to be able to speak to elephants and
spoons . In the movies, Tarzan is played by Keanu Reeves . 

(C)reate mad-lib, (V)iew mad-lib, (Q)uit? Q

Notice that if an input file is not found, either for creating a mad-lib or viewing an existing one, the user is re-prompted. No re-prompting occurs for the output file. If the output file does not already exist, it is created. If it does already exist, its contents are overwritten. (These are the default behaviors in Java.) You may assume that the output file is not the same file as the input file.

When you are viewing an existing mad lib story, you are simply reading and echoing its contents to the console. You do not need to do any kind of testing to make sure that the story came from a mad lib input file; just output the file's contents.

Menu options can be chosen in any order and are not related to each other. The user can choose to view any file, regardless of what file (if any) was just created.

Your program's menu should work properly regardless of the order or number of times its commands are chosen. For example, the user should be able to run each command (such as C or V) many times if so desired. The user should also be able to run the program again later and choose the V option without first choosing the C option on that run. The user should be able to run the program and immediately quit with the Q option if so desired. And so on.

Input Files

You will need to download the example input files from our web site and save them to the same folder as your program. Mad lib input files are mostly just plain text, but they may also contain placeholders. Placeholders are represented as input tokens that begin with < and end with >. Placeholders may also contain additional < and > characters in the text of the placeholder. For example, the file tarzan.txt used in the previous log contains:

Sample input file: tarzan.txt
One of the most <adjective> characters in fiction is named
"Tarzan of the <plural-noun> ." Tarzan was raised by a/an
<noun> and lives in the <adjective> jungle in the
heart of darkest <place> . He spends most of his time
eating <plural-noun> and swinging from tree to <noun> .
Whenever he gets angry, he beats on his chest and says,
" <funny-noise> !" This is his war cry. Tarzan always dresses in
<adjective> shorts made from the skin of a/an <noun>
and his best friend is a/an <adjective> chimpanzee named
Cheetah. He is supposed to be able to speak to elephants and
<plural-noun> . In the movies, Tarzan is played by <person's-name> .

You may assume that each word/token from the input file is separated by neighboring words by a single space. In other words, when you are writing the output, you may place a single space after each token to separate them. You do not need to worry about blank spaces at the end of lines of the output file. It's okay to place a space after each line's last token. Your output mad lib story must retain the original placement of the line breaks from the input story.

Placeholders

Only remove the < and > that surround a placeholder—do not remove or change other instances of < and > that may appear in the file.

Your program should break the input into lines and then into tokens using Scanner objects so that you can look for all its placeholders. Normal, non-placeholder word tokens can be written directly to the output file as-is, but placeholder tokens should cause the user to be prompted using the text inside the placeholder, with the beginning < and ending > removed. The user's response to the prompt is written to the madlib output file, rather than the placeholder itself. You should accept whatever response the user gives, even a multi-word answer or a blank answer.

Sometimes a placeholder has multiple words in it, separated by a hyphen (-), such as <proper-noun>. As your program discovers a placeholder, it should convert any such hyphens into spaces. Any hyphens that appear outside of a placeholder, such as in the other text of the story, should be retained and not converted into spaces.

When prompting the user to fill in a placeholder, give a different prompt depending on whether the text inside the placeholder begins with a vowel (a, e, i, o, or u, case-insensitively). If so, prompt for a response using "an". If not, use "a".

Here are some examples of placeholder prompts that demonstrate the above guidelines:

Placeholder Resulting Prompt
<noun> Please type a noun:
<adjective> Please type an adjective:
<plural-noun> Please type a plural noun:
<Emotional-Actor's-NAME> Please type an Emotional Actor's NAME:

Do not make unnecessary assumptions about the input. For example, other < and > characters may appear inside the file, even in the text inside of placeholders; these should be retained and included in the output. You may assume that a placeholder token will contain at least one character between its < and > (in other words, no file will contain the token <>). You may assume that a placeholder will appear entirely on a single line; no placeholder will ever span across multiple lines.

Creative Portion (mymadlib.txt)

Along with your program, submit a file mymadlib.txt with a story of your own creation in a format suitable for use as input to your program. Look at the sample input on the web site as examples. For full credit, your story should be at least eight (8) lines long and include at least five (5) placeholders.

Development Strategy

As on previous assessments, you will likely want to approach the program one part at a time, rather than trying to write most or all of the program at once. We recommend the following approach:

You may find it easier to hard-code input and/or output files initially, then add prompting later (see below).
  1. View: Write code to read the contents of a file and print them to the console.
    • Even though you have not created any mad libs yet, you can test this code on any file.
  2. Find placeholders: Write code to read in a mad lib file and find and print the placeholders.
  3. Prompt for replacements: Modify your code to prompt the user for a replacement for each placeholder.
  4. File output: Add code to write the contents of the mad lib, including replacements for placeholders, to an output file.
  5. Menu: Add code to create the menu and allow the user to choose between creating and viewing mad libs.

Debugging Tips

Remember to remove any debugging output before submitting.

You may want to initially "hard-code" the input and output filenames; in other words, you may want to just use fixed file names in your code rather than prompting the user to enter the file names. You may also want to temporarily print extra "debug" text to the console while developing your program, such as printing each token or placeholder's text as you read it from the input file. Be sure to remove this extra output before submitting your program.

It is easier to debug this program when using a smaller input file with fewer placeholders. On the course web site we have posted an input file simple.txt with a much shorter mad lib story. You may want to use this as a testing file at first.

If you get an exception, look at the exception's text to find the relevant line number in your file. For example, the exception below was thrown on line 73 of MadLibs.java in the method myMethodName. (The exception was the result of a call to nextLine.)

    Exception in thread "main" java.util.NoSuchElementException: No line found
            at java.util.Scanner.nextLine(Scanner.java:1516)
            at MadLibs.myMethodName(MadLibs.java:73)
            at MadLibs.main(MadLibs.java:20)

Hints

The following suggestions and hints may help you be more successful on this assessment:

  • You will need to use several String methods to search for and replace characters. See textbook sections 3.3 and 4.3-4.4. In particular you may want to use the replace method to replace occurrences of one character with another. For example:
    String str = "mississippi";
    str = str.replace("s", "*"); // str = "mi**i**ippi"
  • Incorrect file input often leads to exceptions. If you get an InputMismatchException, you are trying to read the wrong type of value from a Scanner. If you get a NoSuchElementException, you are trying to read past the end of a file or line.
  • To re-prompt for input file names, you need to know whether a file with a given name exists. You can do this by using methods from File objects as shown in class. The textbook shows an alternative technique for solving the file-not-found problem called a try/catch statement, but should not use this approach on this assessment.

Implementation Guidelines

Like all CSE 142 assessments, this assessment will be graded on all four dimensions defined in the syllabus. Be sure to adhere to the following guidelines:

User Input

This program requires you to process user input, which you must do using a Scanner. All console input should be read using the nextLine method in the Scanner class, not the next method.

File Input/Output

All file input and output in your program should be handled with the File, Scanner, and PrintStream classes. Do not use other methods of file I/O.

Permitted Java Features

For this assessment, you are restricted to Java concepts covered in chapters 1 through 6 of the textbook. In particular, you may NOT use arrays on this assessment.

Code Quality Guidelines

In addition to producing the desired behavior, your code should be well-written and meet all expectations described in the grading guidelines and the Code Quality Guide. For this assessment, pay particular attention to the following elements:

Capturing Structure

You should attempt to eliminate all redundancy in your program, and your main method should be a concise summary of your program's structure, though you may continue to have more code in main than on earlier assessments. In particular, you may have some System.out.println statements in main, and you may include a loop to drive the main menu. However, you main method should NOT directly perform major tasks such as reading an input file or printing a full mad lib. You should also be careful to avoid chaining in your method calls.

Each method should perform a single, coherent task and no method should handle too large a share of the overall program. In addition, to receive the highest grades, your program must include at least four (4) non-trivial methods other than main.

Using Parameters and Returns

Your program should utilize parameters and return values effectively to produce a well-structured program as described above. Your methods should not accept unnecessary or redundant parameters. In particular, you will likely want to have methods that use objects (such as File, Scanner, orPrintStream) as parameters or return values.

Code Aesthetics

Your code should be properly indented, make good use of blank lines and other whitespace, and include no lines longer than 100 characters. Your class, methods, variables, parameters and constants should all have meaningful and descriptive names and follow the standard Java naming conventions. (e.g. ClassName, methodOrVariableName, CONSTANT_NAME) See the Code Quality Guide for more information.

Commenting

Your code should include a header comment at the start of your program, following the same format described in previous assessments. Your code should also include a comment at the beginning of each method that describes that method's behavior. Method comments should also explicitly name and describe all parameters to that method and describe the method's return value (if it has one). Comments should be written in your own words (i.e. not copied and pasted from this spec) and should not include implementation details (such as describing loops or expressions included in the code). See the Code Quality Guide for examples and more information.

Getting Help

If you find you are struggling with this assessment, make use of all the course resources that are available to you, such as:

Collaboration Policy

Remember that, while you are encouraged to use all resources at your disposal, including your classmates, all work you submit must be your own. In particular, you should NEVER look at a solution to this assessment from another source (a classmate, a former student, an online repository, etc.). Please review the full policy in the syllabus for more details and ask the course staff if you are unclear on whether or not a resource is OK to use.

Reflection

In addition to your code, you must submit answers to short reflection questions. These questions will help you think about what you learned, what you struggled with, and how you can improve next time. The questions are given in the "Reflection" slide in the Ed assessment.

Running and Submitting

You can run your program by clicking the "Run" button in Ed. This will compile and execute your code and show you any errors, or the output of your program if it runs correctly. If you believe your output is correct, you can submit your work by clicking the "Mark" button in the Ed lesson. You will see the results of some automated tests along with tentative grades. This grade is not final until you have received feedback from your TA.

You may submit your work as often as you like until the deadline; we will always grade your most recent submission. Note the due date and time carefully—work submitted after the due time will not be accepted.