Lesson 6: User Input and Strings
In this lesson, students are introduced to the string data type as a way of representing arbitrary sequences of ASCII characters. They will use strings to accept input from a user as they work on mastering two new UI elements, the text input and the text area. Students combine these skills to develop a simple Mad Libs® app.
Mad Libs® is a trademark of the Penguin Group (USA) LLC., which does not sponsor, authorize or endorse this site.
Getting Started (15 minutes)
Activity (60 minutes)
Wrap-up (5 Minutes)
Students will be able to:
- Identify strings as a unique data type which contains a sequence of ASCII characters.
- Describe characteristics of the string data type.
- Accept string input in a program.
- Manipulate user-generated string input to generate dynamic output.
For the Students
- Activity Guide - Mad Libs - Activity Guide
- Concatenate - to link together or join. Typically used when joining together text Strings in programming (e.g. "Hello, "+name)
- String - Any sequence of characters between quotation marks (ex: "hello", "42", "this is a string!").
Getting Started (15 minutes)
Explore a Mad Libs app and plan your own
Explore: Students should begin the lesson by moving to the first activity in Code Studio where they will use a Mad Libs app. Over the course of this lesson students will develop skills that will allow them to build their own Mad Libs app by accepting user input as strings. Note: After students move to Code Studio, they should complete the Activity Guide before continuing.
Put a time limit (e.g., 5-10 minutes) on this brainstorming session. It is intended to drive interest in and provide context for the coming activities. Students should feel free to change their ideas later in the lesson when they actually build their Mad Libs app.
Distribute: the Activity Guide - Mad Libs - Activity Guide. Students should use this opportunity to decide on what the theme of their Mad Libs app will be, what text they will accept into their app, and how it will be incorporated into its output. The primary guidelines of the project (also included in the Activity Guide) are:
- The app should be a “how-to” Mad Libs (e.g., “How to take care of your pet ostrich”). Afterwards, you list steps with key components left open for user input. This is primarily to help students quickly conceive of ideas.
- There should be at least 3 steps in their instructions.
- Their app should accept at least 3 pieces of user input.
Before moving into the rest of Code Studio, students should have a rough outline of their project.
Once they have completed their outlines, students should return to Code Studio.
Activity (60 minutes)
App Lab: User Input and Strings
Wrap-up (5 Minutes)
Share: Once students have completed their applications they should share their work with their peers, trying one another’s Mad Libs.
- Mad Lib Demonstration
- (click tabs to see student view)
Getting Text from the User
Up until now, the event-driven apps you have created responded to the user clicking an element or typing a number when you used
promptNum. What if we want the user to provide text instead of a number? You can probably think of many apps and websites that ask you to provide text in order to do something.
In programming, we have to represent text in a specific way to distinguish it from other words in our code, such as variable names. But we'll cover that later...
At the beginning of class you created a Mad Libs on paper, which takes user input in the form of nouns, adjectives, and verbs to create a unique "How-to" manual. You'll be translating your own Mad Libs How-to into an app in this lesson.
- Play with this Mad Libs app a couple of times to see a digital version of the paper game.
- Think about how the final text is created based on the input from the user. How would you describe in words the algorithm for creating it?
The primary data type we have used so far is Numbers. If we want to interact with user-submitted text, however, we'll need to learn about a new data type called a String. A string is a sequence of ASCII characters.
||Strings might look a lot like a variable name but there are many differences.|
||Strings can contain spaces.|
||Strings can contain special characters (and even start with them).|
||Strings might contain only digits. This looks like a number but it is really 2 ASCII characters.|
||Strings might contain no characters.|
|You can store strings in a variable just like a number. In this example the variable name is
Combining Strings: often you will want to combine multiple strings to create one longer string. You can do this with the
+ operator. The formal name of this process is concatenation.
The program you're about to see is a very simple Mad Libs app that uses strings that are created inside the program and saved inside of variables. These strings are then concatenated with other strings to create a Mad Lib.
- The input words of this Mad Lib are currently set to the empty string.
- Add your own input words and run the program to generate the Mad Lib.
Importance of Double Quotes
You may have noticed that the strings we've seen are wrapped in double quotes. These double quotes are not part of the string. Instead this is how you indicate that a sequence of characters is a string and not the name of a variable.
As you start writing programs with strings it is common to generate errors from forgetting to place them in double quotes. We're going to generate some of those errors now so that we can recognize them more easily later.
- This program generates many errors because strings were not placed in quotes.
- Run the program before you change it to see the errors that are generated.
- Add double quotes around all the strings so that the program runs without errors.
Text Input Elements
So far we've been using
promptNum as a simple way to get a number as input. Now that we know a little about strings we are going to create user interface elements that users can use to submit text (i.e. strings) instead. The first and simplest example is
textInput which you can find in Design Mode.
- Add two text input elements to this program, one for the name and one for the age of the user.
- Give your text input elements descriptive and meaningful IDs.
- In Design Mode set their default text to prompt the user for their name and age.
- Compare your app to the example below.
Getting Text Input
As we saw a user can now type inside of a text input whenever they want, but now we'll need a way to access that text. In order to do that you'll need to use the
getText command, which you can now find in the UI Controls tab.
- Read the documentation for
- Add an event handler to the Submit button that fires when your button is clicked.
- Inside the event handler place code that will log the name your user input to the console.
Saving Text Input in Variables
Often we want to save the information we pull in from the user for later use in our program. The best way to do this is to save it in a variable.
- Create two variables inside your event handler to store the age and name of the user.
getText()to update the values stored in each of these variables.
- Change your
console.logstatements to use your variable instead of
Generating Text Output
So far we've been outputting our messages to the console, but now we'd like to display them in the app. In order to do so we're going to be using a new UI element called a
textArea. You can use
setText with a
textArea just like you would with a
If we want to combine user input with default text we can do so with string concatenation. Together with a
textArea we can use this ability to compose longer messages based on user input.
- Add a
textAreato your app and give it a descriptive and meaningful ID.
- Create a variable inside your event handler called
userMessageto hold the full message that will be sent to the user.
- Use string concatenation to compose a message from the user input.
setTextto place your
If you want to change the capitalization of a string you can do so with two new functions
Note that the syntax is similar to
console.log . This is because
toUpperCase really only makes sense as a command when you are using a string, just as
log only makes sense when you are talking about the console. This function evaluates to a new string in which all characters have been made uppercase / lowercase. If you want to update the value in your original variable you'll have to do so explicitly, as in
var myString = "lower case for now"; myString = myString.toUpperCase();
- Update your application so that the user's name is printed in UPPERCASE.
Back to Mad Libs: Design Your App
Now that you've had some practice getting user text and making new strings with it, you're ready to turn your How-to Mad Libs into an app. To get started, you'll set up the layout. There are two main screens:
Screen 1: Collect User Input
- On this screen, you'll use text labels and text input design elements to set up the different words you want the user to provide. - A Next button takes you to Screen 2 to view the full Mad Libs.
Screen 2: View Mad Libs
- On this screen, you'll use the text area design element to create the space where the user's completed Mad Libs will be displayed. - A Play again button takes you back to Screen 1.
|Screen 1:||Screen 2:|
- Create the two screens for your app, including the design elements in each one.
- Requirement: Request at least 3 separate words from the user on Screen 1.
- Create the event handlers for the Next and Play again buttons to respond to clicks.
setScreenin the event handlers to get the screen navigation working.
Update the Text Area with Your Mad Libs Outline
When figuring out how to make progress with a program, it helps to break the problem down into smaller steps and test your program incrementally. So rather than jumping straight to getting the user input and concatenating it with your Mad Libs outline, start first by just making sure that you can get your Mad Libs outline to appear in the text area when the Next button is clicked on the first screen.
But wait! If you just use
setText and pass in the string of your Mad Libs outline, it will look like the screen on the left where all the steps are smushed together. You can use one or more newline characters,
"\n", in your string to create a line break in your text.
|Without newlines||With newlines|
- When the Next button is clicked, you already switch to Screen 2, but now you should also call
setTexton the text area on Screen 2 to your Mad Libs outline. See the images above for one way to temporarily handle the word placeholders.
- Add in newline characters
"\n"in your Mad Libs string to format it.
<samp>console.log("How to Drive\nStep 1.");<br/><br/></samp> *will be displayed as...*<br/><br/> <samp>How to Drive<br/>Step 1.<br/><br/></samp> *...on your console.*
var step1 = "Step 1: ...";<br/> var step2 = "Step 2: ...";<br/> console.log(step1 + "\n" + step2);<br/><br/></samp> *will be displayed as...*<br/><br/> <samp>Step 1: ...<br/>Step 2: ...<br/><br/></samp> *...on your console.*
Make It Mad! Add the User's Text to Your Mad Libs Outline
Now that you have your Mad Libs outline appearing in the text area, it's time to incorporate the user's text to make your Mad Libs come alive.
- Did you pick good ID names for your text input elements? Update them now if you didn't!
- When the Next button is clicked, get the user's text from the text inputs on Screen 1 and store each in a separate variable.
- Use string concatenation to incorporate the user's text into your Mad Labs string before updating the text area on Screen 2.
getTextto get the text from each of the text inputs on Screen 1.
Should I make local or global variables?Remember that the decision to create local variables or global variables is a question of scope. Where will you need to access these variables in your program? If you are only using the variables in the click callback function for the "Next" button, then they can be local variables in that function.
Why Are You Yelling At Me?! toUpperCase and toLowerCase
The main functionality of the Mad Libs app is complete, but there are some finishing touches to add. The user may type input with random letter capitalization, but the Mad Libs output string should be consistently capitalized.
- Pick one or more pieces of the user's input text to transform into "yelling" or emphasize by making it uppercase before displaying it.
- For the other pieces of the user's input text, make it lowercase before displaying it.
HintRemember the rules of updating variables! You can update a variable after first getting its current value and then doing something with it.
song = song.toUpperCase();
Play It Again and Again!
When the user clicks the "Play again" button, the first screen should reset and not show the user's previous text.
- When the "Play again" button is clicked, clear the text from each text input on Screen 1.
- Free play: Add images, or more How-to steps for your Mad Libs, and invite others to play!
HintTry setting the text to the empty string:
CSTA K-12 Computer Science Standards (2011)
CL - Collaboration
- CL.L2:4 - Exhibit dispositions necessary for collaboration: providing useful feedback, integrating feedback, understanding and accepting multiple perspectives, socialization.
CPP - Computing Practice & Programming
- CPP.L2:5 - Implement problem solutions using a programming language, including: looping behavior, conditional statements, logic, expressions, variables and functions.
- CPP.L3A:3 - Use various debugging and testing methods to ensure program correctness (e.g., test cases, unit testing, white box, black box, integration testing)
- CPP.L3A:4 - Apply analysis, design, and implementation techniques to solve problems (e.g., use one or more software lifecycle models).
- CPP.L3A:5 - Use Application Program Interfaces (APIs) and libraries to facilitate programming solutions.
CT - Computational Thinking
- CT.L2:12 - Use abstraction to decompose a problem into sub problems.
- CT.L3A:1 - Use predefined functions and parameters, classes and methods to divide a complex problem into simpler parts.
- CT.L3A:3 - Explain how sequence, selection, iteration, and recursion are building blocks of algorithms.
Computer Science Principles
5.1 - Programs can be developed for creative expression, to satisfy personal curiosity, to create new knowledge, or to solve problems (to help people, organizations, or society).
5.1.1 - Develop a program for creative expression, to satisfy personal curiosity, or to create new knowledge. [P2]
- 5.1.1B - Programs developed for creative expression, to satisfy personal curiosity, or to create new knowledge may have visual, audible, or tactile inputs and outputs.
5.3 - Programming is facilitated by appropriate abstractions.
5.3.1 - Use abstraction to manage complexity in programs. [P3]
- 5.3.1L - Using lists and procedures as abstractions in programming can result in programs that are easier to develop and maintain.
CSTA K-12 Computer Science Standards (2017)
AP - Algorithms & Programming
- 3B-AP-12 - Compare and contrast fundamental data structures and their uses.