top of page

Instructions

Madlibs* is a word game in which words are removed from a story and the player fills in the blanks without knowing the context. The resulting story is often very amusing or nonsensical, so it has been a source of entertainment for many.

Copy and paste the following code into a Java IDE. You will also need to download Std libraries from Princeton University COS126 booksite: https://lift.cs.princeton.edu/java/mac/. When compiling, use javac-introcs, and when running, use java-introcs.

Attached are three sample template stories you can use. Save them to a text file and use the text file name as a command-line argument.

You can also customize your own story by writing your story and indicating which words you want to remove as blanks by typing in '/' followed by the type of word it is, such as /noun or /adjective. Make sure to leave a space before any punctuation. After your story, place three successive hyphens (---) and then duplicate your story beneath it. (See sample stories for format).

*We do not own Madlibs.

public class MadLibs2 {
    public static void main(String[] args) {
        In story = new In(args[0]);
        String need = "";
        String[] input = new String[20];
        String userinput;
        int i = 0;
        while (!story.isEmpty()) {
            String next = story.readString();
            if (next.equals("---")) break;
            if (next.charAt(0) == '/') {
                need = next.substring(1);
                StdOut.println("Give me a(n) " + need);
                userinput = StdIn.readString();
                input[i++] = userinput;
            }

        }
        int j = 0;
        while (!story.isEmpty()) {
            String readstory = story.readString();
            if (readstory.charAt(0) == '/') {
                readstory = input[j++];
            }
            StdOut.print(readstory + " ");
        }
    }
}
 

bottom of page