Have you ever wanted to mix things up a little? Wanted to change the value of a variable each time your program runs? Now we can make that happen!
Using the introcs library, we can ask the user for a number input using the promptNumber function. In order to be able to use this function, we need to import it first. Just like print, we'll need to import promptNumber like this:
import { print, promptNumber } from “introcs”;
To use promptNumber, we have to understand the await keyword.
We put await in front of the name of the prompting function to tell the program to stop and wait for the user’s input. After the user inputs some value, the program will resume.
We use prompting functions to assign a value - input by the user - to a variable. We can do this by declaring a variable, then initializing the variable to the value returned by the prompting function call. This can be done in two separate steps, or all in one go.
The two-step: declare, then initialize
let height: number; height = await promptNumber(“How tall are you?”);
One-step: declaration and initialization in the same line
let height = await promptNumber(“How tall are you?”);
In both of the examples above the variable height would be assigned whatever value was input by the user.
We can use this same process to prompt for strings! For example, we can ask someone for their name by writing something like this:
let name: string; name = await promptString("What's your name?");
Or, we can do it the one-step way too.
let name = await promptString("What's your name?");
In both of the examples above the variable name would be assigned whatever value was input by the user.
How would we prompt the user to enter their age and store it in a variable called age ?