> For the complete documentation index, see [llms.txt](https://scls-cs.gitbook.io/scls-apcs-lab/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://scls-cs.gitbook.io/scls-apcs-lab/if-statements/lab4-chatbot-i-due-oct-23th.md).

# Lab4: Chatbot I(Due Oct 23th)

From [Eliza](https://en.wikipedia.org/wiki/ELIZA) in the 1960s to Siri and [Watson](https://en.wikipedia.org/wiki/IBM_Watson) today, the idea of talking to computers in natural language has fascinated people. More and more, computer programs allow people to interact with them by typing English sentences. The field of computer science that addresses how computers can understand human language is called Natural Language Processing (NLP).&#x20;

NLP is a field that attempts to have computers understand natural (i.e., human) language. There are many exciting breakthroughs in the field. While NLP is a complicated field, it is fairly easy to create a simple program to respond to English sentences.&#x20;

For this lab, you will explore some of the basics of NLP. As you explore this, you will work with a variety of methods of the String class and practice using the if statement.&#x20;

### Step1:  Getting Acquainted with Chatbots

#### Start

Go to <http://demo.vhost.pandorabots.com/pandora/talk-oddcast?botid=ac28c6669e36b194>. Try it out to see how chatbot behaves.&#x20;

You should have several conversations with the your chatbot and observe its responses, for example:

* How does it respond questions like "*Where do you come from?*"
* What is the most interesting response?
* How does it respond to sentences that make no sense, such as "*asdfghjkl*"?

Simple chatbots act by looking for **key words or phrases** and responding to them, for example if you enter "***China***" or "***France***", then it will recognize it as a keyword and respond it with something like: "*Tell me more about China/France*".&#x20;

### Step2:  Introduction to `MagPie` Class.

In this step, you will work on **`MagPie`**, with a simple implementation of a chatbot. You will see how it works with keywords and add keywords of your own.

Open your editor. Create a java class called Magpie, copy and paste the code below. Run the program and see how it behaves:&#x20;

{% code title="Magpie.java" %}

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

   public String getResponse(String statement)
   {
     String response = "";
     if (statement.indexOf("mother") >= 0
                 || statement.indexOf("father") >= 0
                 || statement.indexOf("sister") >= 0
                 || statement.indexOf("brother") >= 0) {
       response = "Tell me more about your family.";
     }
     return response;
   }
}
```

{% endcode %}

{% code title="Main.java" %}

```java
public class Main {
 public static void main(String[] args)
   {
     Magpie maggie = new Magpie();
     System.out.println(maggie.getGreeting());
     
     String s1 = ">My mother and I talked last night.";
     System.out.println(s1);
     System.out.println(maggie.getResponse(s1));
     
     String s2 = ">Do you know my brother?";
     System.out.println(s2);
     System.out.println(maggie.getResponse(s2));
   }
}
```

{% endcode %}

{% hint style="info" %}
You can also use method **contains()** to check if keyword exists.&#x20;

For example, `statement.indexOf("mother") >= 0` is equivalent as `statement.contains("mother").`
{% endhint %}

### Step3: Add one keywords

Now alter the code:

First: 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:

<mark style="background-color:blue;">Statement: I like my cat Mittens.</mark>

<mark style="background-color:blue;">Response: Tell me more about your pets.</mark>

Second: Have the code check that the statement **has at least one character**. If there are no characters, the response should tell the user to enter something.  For example, a possible statement and response would be:

<mark style="background-color:blue;">Statement:</mark>     &#x20;

<mark style="background-color:blue;">Response: Say something, please.</mark>

You can do this by using `trim()` method to remove from the current string all leading and trailing white-space characters, and then checking the length of the trimming string:

```java
String s = "   ";
System.out.println(s.trim().length());    #print 0
```

Test your new keyword by calling `getResponse()` by calling the method with different strings parameters in `main()`. Make sure it prints the correct response before you move to the next step.&#x20;

{% hint style="info" %}
THINK TWICE before your start coding:&#x20;

Where should the new logic be added? You have to make sure the previous keyword in Step 2 is still working.&#x20;
{% endhint %}

### Step4: Add random responses

Now we can detect several keywords and give the matching response. But what if the statement doesn't match any of the keywords? Add some random responses **if the statement doesn't contain any keyword**. An example code is below:&#x20;

```java
public String getRandomResponse()
   {
     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;
}
```

Add **getRandomResponse()** to Magpie.java, then call this method in **`getResponse()`** to make it work. (Think: where should you put the method?)

For example, the possible statements and responses would be:

<mark style="background-color:blue;">Statement: blah blah blah.</mark>

<mark style="background-color:blue;">Response: You don't say.</mark> *(give a random response)*

<mark style="background-color:blue;">Statement: My brother is in town.</mark>

<mark style="background-color:blue;">Response: Tell me more about your family.</mark> *(match the keyword "brother")*

Again, test your "**random response generator**" by calling `getResponse()` in `main().` Make sure it prints the correct response before you move to the next step.

### Step5: Write your own random response

Write your own **getRandomResponse()** method. You can work on top of the method provided, or write a completely new method. **It should contain at least 8 random responses.**&#x20;

### Step6: Test your chatbot!

Testing is as important as coding. The following code uses the `Scanner` class to read input from the user. It is similar to the input() function in Python. The `Scanner` class is not on the AP CS A exam, but it will be used in Lab4.&#x20;

Copy and paste the code in Main.java and test your chatbot. You can type anything in console and press Enter. The chatbots will keep talking to you until you enter "Bye", then it will quit itself.&#x20;

{% code lineNumbers="true" %}

```java
import java.util.Scanner;

public class Main {
 public static void main(String[] args)
   {
      Magpie maggie = new Magpie();

      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();
      }
   }
}
```

{% endcode %}

{% hint style="info" %}
Line 9\~10 is to use Scanner class to get user's input and store it as a String.
{% endhint %}

### Submit

If you would like to add additional features to your chatbot, feel free to do so! Be sure to save everything before you submit or close your browser! You will work on an updated version of chatbot in the next lab.

Submit all your work on 钉钉作业本 by Oct 23th, 10PM.&#x20;

####
