关键词 > Java代写

Lab 09: Chained and Nested Conditionals, Strings

发布时间:2021-03-29



Lab 09: Chained and Nested Conditionals, Strings


REMEMBER TO SUBMIT ONE DOCUMENT IN BLACKBOARD INCLUDING CODE (WITH APP LAB SHARE LINK) AND ANSWERS TO QUESTIONS.


To make your digital assistant respond to user input, you must evaluate keywords within the input using conditionals (also known as selection). More complex conditional logic, like chained and nested if statements, will enable your digital assistant to generate unique responses to a specific set of keywords.


Adding Intelligence Using Conditionals - So far the digital assistant you created responds with the same message no matter what the user types. Let's look at how to make the digital assistant smarter.


In the last lecture we learned about if and if-else statements. These allow us to make decisions. In the digital assistant we want to make decisions based on keywords in what the user types. In the Age Bot example in Lab 8 we might check for the user question including the words “driving” “voting” “high school” or “work” to determine a response (or even the sub-words “driv” “vot” instead of “driving” “voting”.


So we are not checking for exact equality with something the user types, but checking if what they type includes a certain substring. There is an App Lab function called “includes” This function can be used to check if one string appears anywhere inside of another. includes is a function that returns a boolean. In other words, when the function runs it will evaulate to either true or false. This function can be used anywhere you would normally use a boolean expression. Just like toUpperCase and toLowerCase this function is called using dot notation.


var name=”John Smith”;

console.log(name.includes(“John”)); // should output true


You've actually seen a few functions that return a value before this. randomNumber is a function that returns a number and getText is a function that returns a string. In every case we've used these functions as if they were the data type they return (or evaluate to). Notice that in block mode these functions don't have the connectors that other commands do since they will be used as a piece of data within another function. Read the documentation for includes and see the below Age Bot example.


// Age Bot example

var defaultResponse = "I am not sure.";

onEvent("userQuestion", "change", function() {

  var q = getText("userQuestion");

  generateResponse(q);

});

function generateResponse(question) {

  setText("userQuestion", "");


  if (question.includes(“driv”))

    setText("response", "User: "+question+"\nAge Bot: The driving age is 16”);

  else

    setText("response", "User: "+question+"\nAge Bot: "+ defaultResponse);

}


1. (1 point) Add one if-else statement to your personal digital assistant from Lab 8 to check for a particular word in the user text and respond accordingly.


We want our personal digital assistant to reply correctly to many different user questions, not just one. To program this we can chain a series of if-else statements together


Chained Conditionals

● Chained conditionals are used to create multiple alternative conditions. Chained if statements are evaluated from top to bottom - the program will execute the first if statement that evaluates to true, and skip over the remaining statements. This means that only one of the if statement clauses will ever be evaluated even if there is more than one statement that evaluates to true.

○ Example: When ordering a drink at a restaurant, a person could say, “If you have pepsi products, I’d like a Sierra Mist. Otherwise, if you have coke products I’d like a Sprite. Otherwise I’d like water.”

● While it is not necessary to have an ‘else’ statement at the end, it is often helpful to have a ‘catch all’ statement. In the example above, this is the, “otherwise I’d like water” statement. If server did not have Pepsi or Coke products and the last statement did not exist, the server would still not know what beverage to bring to the customer.

● The syntax for a chained conditional looks similar to the example below. There may be as many “else if” statements as necessary.


if (condition 1) {

// do special action 1

} else if (condition 2) {

// do special action 2

} else {

// do default action

}


2. Digital Assistant V.2 (4 points)

Starting with the Digital Assistant from above, add a series of chained if statements to your “generateResponse” function  (that is called from the event handler), to check the user input for at least 4 different key words in your subject area (see the work you did in Lab 8) and have Digital Assistant respond appropriately. Leave the default response for the last “else” statement.


What if the user types Voting instead of voting? These are two different strings to the computer and therefore it won't recognize they are the same. We want Age Bot to treat words the same ignoring the case of the letters. We can do this using the string command toLowerCase to make a new variable containing the user input in all lower case, and check that variable using the includes function in your chained if-else statements. This is your Digital Assistant V.2


Nested Conditionals

● Now that you can pick a keyword out of a sentence, you will start to explore the options you have when there are multiple keywords in a sentence.

● Nested conditionals allow your digital assistants to make a decision based on another decision. A nested conditional is made by writing an if statement inside another if statement. Notice this is different from chaining if-else statements.

● Each digital assistant specializes in a topic. The digital assistant can also specialize in several sub-topics. For example, if my digital assistant specializes in the topic of food recipes, it can also be knowledgeable in the sub-topics of pizza, soup, and salad recipes.


if (sentence.includes("pizza")) {

if (sentence.includes("Hawaiian")) {

write("Hawaiian pizza is made with ham and pineapple");

} else if (sentence.includes("vegan")) {

write("Vegan pizza has no animal products - i.e. meat

or cheese or butter");

} else {

write("Pizza is usually made from a flat dough topped

with tomato sauce, cheese, meat, and/or vegetables");

}

} else if (sentence.includes("soup")) {

// details about soup

...


3. Digital Assistant V.3 (5 points)

Starting with the Digital Assistant V.2, add nested if statements to at least two of your response options. So for an ageBot for example may need to handle different driving ages for different states, once you find the keyword “driving” you can check (nested if) for keywords for particular states and generate the appropriate response. This is your Digital Assistant V.3


String Functions

You know how to detect a single word or phrase within a string. This is very useful for your digital assistant, but what if your digital assistant is expecting the keyword “programming” and the user types “Programming” or “PrOgraMMinG?” Your digital assistant should still treat these the same. What about if you want to know if the keyword is at the beginning or end of a sentence? How about if you want to use part of the input sentence as part of your output? We will explore many types of string manipulation today.


Vocabulary

● String: a sequence of characters delimited with quotes.

● Index: a number that specifies a location within a string. The first character in the string has an index of index 0, and the characters are enumerated from there sequentially.


Challenge 1: (1 point) string.indexOf(substring)

We can use string.indexOf(substring) to indicate whether or not a word exists within a string. The value -1 indicates that the word does not exist within a string. Any value greater than -1 indicates that the word does exist within a string. What do all those positive values mean? A positive value from string.indexOf(substring) indicates the first index of the substring.


The string learn contains the sequence of characters “I love App Lab!”. The index of each character is shown in the table below:


0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

I

 

l

o

v

e

 

A

p

p

 

L

a

b

!


Misconception Alert

It’s easy to confuse the indexing of a string. Remember: the first character in a string is indexed at position 0, the second character is indexed at position 1, and so on.


Create a table of index positions for the string var s="Madam I’m Adam.";


0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


What is the index of the first occurrence of each of the following characters:


                “M”                                  “A”

 

                “ ”                                    “.”

 

                “a”                                   “k”


Confirm your expectation using the s.indexOf() function in App Lab.


Challenge 2: (2 points) str.length

Unlike str.indexOf(), str.length is not a function. Instead, it is an attribute that all strings have and its value is the number of characters in the string.

1. What is the length of the following strings? Check your answer in App Lab by using str.length.


a. “Hello World”

b. “Computer science rocks!”

c. “I promise to do my homework every day.”


2. In App Lab, complete the code below that writes “yes” to the console if a string has a length greater than 10, or “no” if it is less than or equal to 10. Test your function using two strings, one that will satisfy each conditional option.


var short = "short";

var long = "this is a very long input";

var tenChars = "ten chars.";


function isLongerThanTen(string) {

 


}

// call your function here on each of the three strings


Challenge 3: (2 point) str.substring(start, end)

The str.substring() function returns part of a string from index start to one before index end.

1. What parameters do you need to use to get “Adam” from the string s in Challenge 1?
var s="Madam I’m Adam."; Test this in App Lab.


What parameters do you need to use to get “adam” from the string s in Challenge 1?
var s="Madam I’m Adam."; Test this in App Lab.


2. In App Lab, complete the function findBeginNder() to get the first occurrence of the strings "begin" and "nder" from a sentence no matter where in the sentence they exist. You will need to use indexOf and substring. Print the strings and their index to the console. Test the function on the following inputs

a. Wisdom begins with wonder.

b. Does wisdom begin with wonder?

c. Yoda says: 'begin with wonder wisdom does.’

d. #nderbegin


var test1 = "Wisdom begins with wonder.";

var test2 = "Does wisdom begin with wonder?";

var test3 = "Yoda says: 'begin with wonder wisdom does.’";

var test4 = "#nderbegi";  // will not find begin


function findBeginNder(input) {

  var beginIndex = // find the index of "begin"

  var nderIndex = // find the index of "nder"

  var beginString = // get the substring "begin"

  var nderString = // get the substring "nder"


  console.log(beginIndex + " " + beginString + " " + nderIndex + " " + nderString);

}


findBeginNder(test1);

findBeginNder(test2);

findBeginNder(test3);

findBeginNder(test4);


Challenge 4: (2 points) Reordering Strings

Sometimes we want to reorder information in strings. In App Lab, write a function that takes a name (first last) and reorders it (last, first) and outputs it to the console.

Example: “Alan Turing” → “Turing, Alan”

Hint: Use substrings, length, index of, and your prior knowledge of concatenation.


Digital Assistant V.4 (3 points)

Starting with the Digital Assistant V.3, add string functions to support the following enhancements to make our digital assistant appear smarter! This is your Digital Assistant V.4


If a user inputs the phrase “What is <phrase>?” and your digital assistant does not match any keywords, your digital assistant should respond “I don’t know what <phrase> is.”  Insert this keyword check as second to last in your chained conditionals. Leave your old default response at the end of the chained if-else conditionals.


Example:

User: What is football?

DA: I don’t know what football? is.


User: What is William Shakespeare’s Romeo and Juliet?

DA: I don’t know what William Shakespeare’s Romeo and Juliet? is.