Magpie Chatbot Lab

From CS Awesome 2CC BY-NC-SA 4.0Original page

Java1 class period4 exercisesNot autograded

Files

README.mdDownload

Magpie Chatbot Lab

Each coding exercise has its own folder. Open its .java file and press Run to try it.

This is the original College Board Magpie lab from 2014. There is a new Magpie 2.0 lab as of 2025 which is available in the AP Classroom. It is very similar to the following lab, but must be done within AP Classroom.

For the original Magpie lab, here is the College Board Magpie Chatbot Lab Student Guide.

The Magpie lab creates a simple chatbot and provides practice with String methods and conditionals. A chatbot is a computer program that tries to hold a conversation with a user. The exercises below will walk you through the activities in the original Magpie chatbot lab.

Activity 1: Exploring Chatbots

The first activity in Magpie is to explore some existing chatbots. We encourage you to work in pairs or groups on this activity.

  1. Working in pairs or groups, try out some chatbots, for example:
    • ELIZA the therapist bot from the 1970s
    • Cyberduck, a chatbot based on ELIZA
    • Modern chatbots which use AI and machine learning. Duck.ai does not require an account. Many schools also provide Gemini.
  2. Record the chatbot response to each of the following.
    • Where do you come from?
    • asdfghjkl;
    • My mother and I talked last night.
    • The weather is nice.
    • I said no!
  3. Ask the chatbot other questions.
    • Record the most interesting response.
    • Record the most peculiar response.
  4. Work with another student or group to have two chatbots chat with each other. Type the responses from one chatbot into the input area for the other and vice-versa.
  5. Keywords: Some chatbots look for particular keywords and respond based on those keywords. What are some of the keywords that your chatbot seems to be responding to? Why do you think it responds to those keywords?

Activity 2: Running Simplified Magpie Code

The College Board activity asks you to enter input using the Scanner class and record the responses. But, instead you can run this simplified version below and just call the getResponse method with each string as input as shown in the main method below.

In this lab, the main method creates a Magpie object called maggie, and calls its methods maggie.getGreeting() and maggie.getResponse(input) where the input can be one of the following strings as input and a response is printed out.

  • My mother and I talked last night.
  • I said no!
  • The weather is nice.
  • Do you know my brother?

Run the following code and see the responses to these 4 inputs.

When different methods are called from the main method, the control flows to these methods and then comes back to main exactly where it was left when the methods finish. Click on the cool [Java visualizer Chatbot](http://www.pythontutor.com/visualize.html#code=public+class+Magpie2%0A%7B%0A+++public+String+getGreeting(%29%0A+++%7B%0A+++++return+%22Hello,+let's+talk.%22%3B%0A+++%7D%0A%0A+++public+String+getResponse(String+statement%29%0A+++%7B%0A+++++String+response+%3D+%22%22%3B%0A+++++if+(statement.indexOf(%22no%22%29+%3E%3D+0%29+%7B%0A+++++++response+%3D+%22Why+so+negative%3F%22%3B%0A+++++%7D+else+if+(statement.indexOf(%22mother%22%29+%3E%3D+0%0A+++++++++++++++++%7C%7C+statement.indexOf(%22father%22%29+%3E%3D+0%0A+++++++++++++++++%7C%7C+statement.indexOf(%22sister%22%29+%3E%3D+0%0A+++++++++++++++++%7C%7C+statement.indexOf(%22brother%22%29+%3E%3D+0%29+%7B%0A+++++++response+%3D+%22Tell+me+more+about+your+family.%22%3B%0A+++++%7D+else+%7B%0A+++++++response+%3D+getRandomResponse(%29%3B%0A+++++%7D%0A+++++return+response%3B%0A+++%7D%0A%0A+++private+String+getRandomResponse(%29%0A+++%7B%0A+++++final+int+NUMBER_OF_RESPONSES+%3D+4%3B%0A+++++double+r+%3D+Math.random(%29%3B%0A+++++int+whichResponse+%3D+(int%29(r+*+NUMBER_OF_RESPONSES%29%3B%0A+++++String+response+%3D+%22%22%3B%0A%0A+++++if+(whichResponse+%3D%3D+0%29+%7B%0A+++++++response+%3D+%22Interesting,+tell+me+more.%22%3B%0A+++++%7D+else+if+(whichResponse+%3D%3D+1%29+%7B%0A+++++++response+%3D+%22Hmmm.%22%3B%0A+++++%7D+else+if+(whichResponse+%3D%3D+2%29+%7B%0A+++++++response+%3D+%22Do+you+really+think+so%3F%22%3B%0A+++++%7D+else+if+(whichResponse+%3D%3D+3%29+%7B%0A+++++++response+%3D+%22You+don't+say.%22%3B%0A+++++%7D%0A+++++return+response%3B%0A+++++++%7D%0A%0A+++public+static+void+main(String%5B%5D+args%29%0A+++%7B%0A+++++Magpie2+maggie+%3D+new+Magpie2(%29%3B%0A%0A+++++System.out.println(maggie.getGreeting(%29%29%3B%0A+++++System.out.println(maggie.getResponse(%22My+mother+and+I+talked+last+night.%22%29%29%3B%0A+++++System.out.println(maggie.getResponse(%22I+said+no!%22%29%29%3B%0A+++++System.out.println(maggie.getResponse(%22The+weather+is+nice.%22%29%29%3B%0A+++++System.out.println(maggie.getResponse(%22Do+you+know+my+brother%3F%22%29%29%3B%0A+++%7D%0A%7D&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=java&rawInputLstJSON=%5B%5D&curInstr=9) below to step through the code.

public class Magpie2
{
    public String getGreeting()
    {
      return "Hello, let's talk.";
    }

    public String getResponse(String statement)
    {
      String response = "";
      if (statement.indexOf("no") >= 0)
      {
        response = "Why so negative?";
      }
      else if (statement.indexOf("mother") >= 0
                  || statement.indexOf("father") >= 0
                  || statement.indexOf("sister") >= 0
                  || statement.indexOf("brother") >= 0)
      {
        response = "Tell me more about your family.";
      }
      else
      {
        response = getRandomResponse();
      }
      return response;
    }

    private String getRandomResponse()
    {
      final int NUMBER_OF_RESPONSES = 4;
      double r = Math.random();
      int whichResponse = (int)(r * NUMBER_OF_RESPONSES);
      String response = "";

      if (whichResponse == 0)
      {
        response = "Interesting, tell me more.";
      }
      else if (whichResponse == 1)
      {
        response = "Hmmm.";
      }
      else if (whichResponse == 2)
      {
        response = "Do you really think so?";
      }
      else if (whichResponse == 3)
      {
        response = "You don't say.";
      }
      return response;
    }

    public static void main(String[] args)
    {
      Magpie2 maggie = new Magpie2();

      System.out.println(maggie.getGreeting());
      System.out.println(maggie.getResponse("My mother and I talked last night."));
      System.out.println(maggie.getResponse("I said no!"));
      System.out.println(maggie.getResponse("The weather is nice."));
      System.out.println(maggie.getResponse("Do you know my brother?"));
    }
 }

As you can see the getResponse method of Magpie2 looks for certain keywords like "mother" and "brother". Why do you think the response to “Do you know my brother?” isn’t “Tell me more about your family.”? Discuss this with partner in pairs and see if you can figure it out.

The response to “The weather is nice.” is one of the random responses. Look at the code to see how the if statement assigns a value to the response and returns that response. The method getRandomResponse generates a random number and uses that to assign the response. Modify the code above to add other random responses.

Exercise 1

Run to see the results. Try changing the input in main.

Open the 01-lc-magpie2 folder and edit Magpie2.java. This one is not graded, so check it yourself.

Exercises

Alter the code above or in your own IDE (see section below) to do the following. We encourage you to work in pairs.

  • Have it respond “Tell me more about your pets” when the statement contains the word “dog” or “cat”. For example, a possible statement and response would be:
    • Statement: I like my cat Mittens.
    • Response: Tell me more about your pets.
  • Have it respond favorably when it sees the name of your teacher. Be sure to use appropriate pronouns! For example, a possible statement and response would be:
    • Statement: Mr. Finkelstein is telling us about robotics.
    • Response: He sounds like a good teacher.
  • Have the code check that the statement has at least one character. You can do this by using the trim method to remove spaces from the beginning and end, and then checking the length of the trimmed string. If there are no characters, the response should tell the user to enter something. For example, a possible statement and response would be:
    • Statement:
    • Response: Say something, please.
  • Add two more noncommittal responses to the possible random responses.
  • Pick three more keywords, such as “no” and “brother” and edit the getResponse method to respond to each of these.
  • What happens when more than one keyword appears in a string? Try the input My **mother** has a **dog** but **no** cat. Which response did you get – was it the one about family or the one about pets or the negative one for no? Change the order of your if-else-if statements to make it so that one of the other responses is selected and try running it again.

What happens when a keyword is included in another word? Consider statements like “I know all the state capitals” which contains no and “I like vegetables smothered in cheese” which contains mother. Explain the problem with the responses to these statements.

Discuss this with your class, or answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/magpie-chatbot-lab-1.html#short-lab1b1

Activity 2: Actual Code - (Optional)

You can do all of Activity 2 with the actual code using the Scanner class for input instead if you prefer.

Or you can copy and paste in the code from below into any Integrated Development Environment (IDE) like DrJava or JGrasp to run on your computer.

Here is the code for MagpieRunner2.java.

import java.util.Scanner;

/**
 * A simple class to run the Magpie class.
 *
 * @author Laurie White
 * @version April 2012
 */
public class MagpieRunner2
{

    /** Create a Magpie, give it user input, and print its replies. */
    public static void main(String[] args)
    {
        Magpie2 maggie = new Magpie2();

        System.out.println(maggie.getGreeting());
        Scanner in = new Scanner(System.in);
        String statement = in.nextLine();

        while (!statement.equals("Bye"))
        {
            System.out.println(maggie.getResponse(statement));
            statement = in.nextLine();
        }
    }
}

Here is the code for Magpie2.java.

public class Magpie2
{
    /**
     * Get a default greeting
     *
     * @return a greeting
     */
    public String getGreeting()
    {
        return "Hello, let's talk.";
    }

    /**
     * Gives a response to a user statement
     *
     * @param statement the user statement
     * @return a response based on the rules given
     */
    public String getResponse(String statement)
    {
        String response = "";
        if (statement.indexOf("no") >= 0)
        {
            response = "Why so negative?";
        } else if (statement.indexOf("mother") >= 0
                || statement.indexOf("father") >= 0
                || statement.indexOf("sister") >= 0
                || statement.indexOf("brother") >= 0)
        {
            response = "Tell me more about your family.";
        }
        else
        {
            response = getRandomResponse();
        }
        return response;
    }

    /**
     * Pick a default response to use if nothing else fits.
     *
     * @return a non-committal string
     */
    private String getRandomResponse()
    {
        final int NUMBER_OF_RESPONSES = 4;
        double r = Math.random();
        int whichResponse = (int) (r * NUMBER_OF_RESPONSES);
        String response = "";

        if (whichResponse == 0)
        {
            response = "Interesting, tell me more.";
        }
        else if (whichResponse == 1)
        {
            response = "Hmmm.";
        }
        else if (whichResponse == 2)
        {
            response = "Do you really think so?";
        }
        else if (whichResponse == 3)
        {
            response = "You don't say.";
        }

        return response;
    }
}

Activity 3: Better Keyword Detection

This activity introduces you to some new String methods including some that are not on the exam, but are useful. Your teacher will tell you whether your class is doing this activity or not.

More String Methods

Run the StringExplorer below. It currently has code to illustrate the use of the indexOf and toLowerCase methods. Do they do what you thought they would? The method indexOf is on the exam and the method toLowerCase is not. Why do you think you might want to change the string to all lowercase characters? Why doesn’t the value of sample change?

Exercise 2

Run the code. Why do you think you might want to change the string to all lowercase characters? Why doesn’t the value of sample change? Do string methods change the string? Try some other string methods.

Open the 02-lc-strEx folder and run StringExplorer.java. It is an example, so it has no tests.

Open the API for String in Java documentation in another tab. Scroll down to the Method Summary section and find the indexOf(String str) method. Follow the link and read the description of the indexOf method.

Check your understanding: What value is returned by indexOf if the substring does not occur in the string? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/magpie-chatbot-lab-1.html#fill-lab1b1

Copy the following lines to StringExplorer in the exercise above in the main method above to see for yourself that indexOf behaves as specified:

int notFoundPsn = sample.indexOf("slow");
System.out.println("sample.indexOf(\"slow\") = " + notFoundPsn);

Read the description of indexOf(String str, int fromIndex). Add lines to StringExplorer that illustrate how this version of indexOf differs from the one with one parameter.

Better Keyword Detection

In activity 2, you discovered that simply searching for collections of letters in a string does not always work as intended. For example, the word “cat” is in the string “Let’s play catch!”, but the string has nothing to do with the animal. In this activity, you will trace a method that searches for a full word in the string. It will check the substring before and after the string to ensure that the keyword is actually found.

Take a look at the findKeyword method below. It has a while loop in it which we haven’t seen before. A while loop repeats the code in the block below it while a condition is true. A block is all the code inside of an open curly brace { and a close curly brace }.

private int findKeyword(String statement, String goal,
        int startPos)
{
   String phrase = statement.trim();
   // The only change to incorporate the startPos is in
   // the line below
   int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(),
                                          startPos);

   // Refinement--make sure the goal isn't part of a word
   while (psn >= 0)
   {
      // Find the string of length 1 before and after
      // the word
      String before = " ", after = " ";
      if (psn > 0)
      {
         before = phrase.substring(psn - 1, psn).toLowerCase();
      }
      if (psn + goal.length() < phrase.length())
      {
         after = phrase.substring(
                  psn + goal.length(),
                  psn + goal.length() + 1)
                  .toLowerCase();
      }

      /* determine the values of psn, before, and after at this point */

      // If before and after aren't letters, we've
      // found the word
      if (((before.compareTo("a") < 0) ||
           (before.compareTo("z") > 0)) // before is not a letter
          && ((after.compareTo("a") < 0) ||
              (after.compareTo("z") > 0)))
      {
          return psn;
      }

      // The last position didn't work, so let's find
      // the next, if there is one.
      psn = phrase.indexOf(goal.toLowerCase(),psn + 1);

   }

   return -1;
}
if (findKeyword(statement, "no") >= 0)
{
   response = "Why so negative?";
}
Exercise 3

Modify the code to print the values of psn, before, and after right after the comment on line 100 in the findKeyword method. Record each of the values in a table. The College Board student guide for the Magpie Chatbot Lab has a table on page 8 that can be printed.

Open the 03-lc-magpie3 folder and edit Magpie3.java. This one is not graded, so check it yourself.

Exercise: Use the new method

Repeat the changes you made to the program in Activity 2, using this new method to detect keywords.

Questions: Prepare for the next activity

Single keywords are interesting, but better chatbots look for groups of words. Consider statements like “I like cats,” “I like math class,” and “I like Spain.” All of these have the form “I like something.” The response could be “What do you like about something?” The next activity will expand on these groups. You will get to add one of your own, so it’s a good idea to start paying close attention to common phrases in your own conversations.

Activity 4: Responses that Transform Statements

If your class has time, your teacher may have you do Activity 4 below.

As stated previously, single keywords are interesting, but better chatbots look for groups of words. Statements like “I like cats”, “I like math class”, and “I like Spain” all have the form “I like something”. The response could be “What do you like about something?” This activity will respond to groupings of words.

Try each of the following as the value for the statement in the main method and see what they print.

  • I want to understand French.
  • Do you like me?
  • You confuse me.

You can also step through the code in the Java visualizer.

Exercise 4

Try Mapgpie4 below.

Open the 04-magpie4-activity folder and run Magpie4.java. It is an example, so it has no tests.

Exercises:

In this activity, the chatbot is altered to look not only for keywords, but also specific phrases. Magpie4.java adds two new methods, transformIWantToStatement and transformYouMeStatement and getResponse has been modified to add tests to find “I want to something” statements and “You something me” statements.

Look at the code. See how it handles “I want to” and you/me statements.

Then add two new methods, transformIWantStatement and transformIYouStatement, and calls to each as described below.

  • In a method transformIWantStatement, have it respond to “I want something” statements with “Would you really be happy if you had something?” You can use the already written transformIWantToStatement method as a guide. In doing this, you need to be careful about where you place the call to the method so it calls the right one. Test with the following:
    • Statement: I want fried chicken.
    • Response: Would you really be happy if you had fried chicken?
  • In a method transformIYouStatement, have it respond to statements of the form “I something you” with the restructuring “Why do you something me?”. You can use the transformYouMeStatement method as a guide. Test with the following:
    • Statement: I like you.
    • Response: Why do you like me?

Find an example of when this structure does not work well. How can you improve it?

Mixed Up Code Practice

Check your understanding: The following program segment should print 4 random responses using if/else statements, but the blocks have been mixed up. — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/magpie-chatbot-lab-1.html#chat-labp1

For teachers

Magpie Chatbot Lab

Students read CSAwesome2's “Magpie Chatbot Lab” in CS Room and work through its 4 Java coding exercises (not graded).

  • Time: 1 class period
  • Tests: none

Goals

  • Practice for Unit 2: Selection and Iteration.

Before class

In class

  1. Students read README.md. Questions that need CS Awesome's interactive widgets link back to it.
  2. Students run the examples in exercises 01–04, each in its own folder.

Exercises

FolderFileGradingTests
01-lc-magpie2Magpie2.javaNot graded; students check it themselves0
02-lc-strExStringExplorer.javaExample, not graded0
03-lc-magpie3Magpie3.javaNot graded; students check it themselves0
04-magpie4-activityMagpie4.javaExample, not graded0