8.4 Input and Output Statements
In order for a computer program to perform any useful work, it must be able to communicate with the outside world. The process of communicating with the outside world is known as input/output or I/O. Watson JavaScript includes two output statements for displaying information on the computer’s screen, and two input statements – one for reading in text input, the other for reading in numeric input. Most imperative languages include mechanisms for performing other kinds of I/O such as detecting where the mouse is pointing and accessing the contents of a disk drive.
The two output statements included in Watson JavaScript are document.write and document.writeln. These statements are of the general form:
where an “expression” can be a constant, a variable, a function call, or a collection of these things connected by appropriate operators. Both the document.write and document.writeln statements display the value of an expression on the computer screen. The only difference between the two is that document.writeln starts a new line after printing the value on the screen. For this reason, document.writeln is pronounced as if it were written “document write line”.
Figure 8.4 contains a simple Watson JavaScript program together with the output produced by the program.
Figure 8.4: A Watson JavaScript program and its output
This program consists of a single instruction:
document.writeln(“Hello World!”);
Since the expression contained in this document.writeln statement is the text constant “Hello World!”, the program displays the value of that constant on a line by itself, producing the output:
Hello World!
The program of Figure 8.5 illustrates the difference between document.write and document.writeln. It also introduces numeric expressions and the concept of sequence. The program consists of three output statements: two document.write statements followed by a document.writeln. When run, it produces the following line of output.
There are 13 cookies in a baker’s dozen.
To understand how this program works we must first recall from our discussion of the Watson Graphics Language that the statements of a program are executed one after another in the order, or sequence, they appear. Hence, the first statement to be executed is:
document.write(“There are ”);
This statement prints the following characters on computer’s display screen:
There are
While it is not apparent in the line shown above, if you look closely at the statement, you will see that a space, or “blank” is supposed to follow the word “are”. Because this statement is a “write” and not a “writeln” a new line of output was not begun after these characters were displayed. Thus, the next program output will immediately follow the characters just printed, on the same line.
Program definition
| |||||||
| |||||||
| |||||||
| |||||||
|
Internal Variables
Program input/output behavior
Figure 8.5: A Watson JavaScript program that outputs both text and numbers
The position that the next character will be printed in is often indicated by the underscore symbol, _. Using this symbol, it is easy to see that a space does indeed follow the word “are” in the output.
There are _
The next statement to be executed is:
document.write(12 + 1);
This statement contains the mathematical expression 12 + 1 which evaluates to the number 13. Since “Write” and “WriteLn” statements display the value of an expression, and not the expression itself, 13 will be printed next. The program’s output now looks like the following, with the print position immediately following the 13.
There are 13 _
It is important that you pay close attention to whether or not an expression is surrounded by quote marks when attempting to determine its value. If an expression is surrounded by quote marks then the characters between those quotes represent the value of the expression. If the expression is not quoted, then its value must be determined by performing the operations specified in the expression. Thus,
but
Continuing with the example, the third and last statement of the program
document.writeln(“ cookies in a baker’s dozen.”);
will now be executed to produce the following:
Note that this statement is a “writeln” rather than a “write”, so it moves the print position to the next line. Always remember that document.writeln statements begin a new line after they print the value of their expression on the screen, not before printing.
Another important point to note about this statement is that the text string it contains begins with a blank. This is important since the print position was located immediately after the 13 when this statement was executed. If the leading blank had been omitted from the string, the program would have produced the following result:
There are 13cookies in a baker’s dozen.
In a sense, Watson JavaScript programs, such as those of Figures 8.4 and 8.5, are quite similar to the Watson Graphics Language (WGL) programs we studied in Chapter 6. Both Watson JavaScript and WGL belong to the imperative paradigm and both are capable of generating output. As we continue our study of Watson JavaScript, many additional similarities will become apparent.
There are also significant differences between these languages. For example, the output statements of Watson JavaScript are document.write and document.writeln as opposed to draw and erase in WGL. Another difference between Watson JavaScript and WGL is that every WGL program always produces exactly the same output every time it is run. When using WGL, every unique drawing or animation requires that a separate program be written. Likewise, the Watson JavaScript programs of Figures 8.4 and 8.5 will always produce the same output each time they are run.
Most programs of lasting value, however, generate different results, or outputs, depending on the inputs they are given. The primary reason that WGL programs always produce the same result each time they are run is that the language lacks an input statement. Watson JavaScript does not suffer from this limitation. It provides two input instructions – one for reading in text data, and one for reading in numeric data.
The general format of the text input statement is:
variable = prompt(message,defaultValue);
In this statement, variable will be replaced with an actual program variable that has been declared to be of type “Text”. This variable will hold the data entered by the user. The message field will be replaced by a text string that contains a brief message designed to prompt the user to enter the appropriate value. The defaultValue field is used to specify a default text string that will be assigned to the variable in case the user fails to enter any data when prompted to do so.
Thus, the text input statement:
firstName = prompt("Please enter your first name.", "unknown");
will prompt the user to enter his or her first name by displaying an input dialog box on the screen with the prompt “Please enter your first name.” next to the input field. Whatever characters the user types in will be stored in the variable firstName. If the user simply dismisses the input dialog without entering any characters, firstName will be assigned the text string “unknown” in order to indicate that the user’s first name is unknown.
The Watson JavaScript numeric input statement is similar. It has the form:
variable = parseFloat(prompt(message,defaultValue));
The most obvious difference between Watson JavaScript’s text input statement and its numeric input statement is that the numeric input statements include the phrase “parseFloat()”. This phrase insures that Watson JavaScript will supply a numeric entry pad to the end user so that only numeric data can be entered. In addition, this statement requires that variable be replaced with a program variable declared to be of type “numeric”. Also, while the message will continue to be a text string, the defaultValue must be a numeric constant – rather than a text constant.
The numeric input statement
age = parseFloat(prompt(“Enter your age.”,0));
will prompt the user to enter his or her age by displaying a numeric entry pad on the screen with the prompt “Enter your age.” next to the input field. The number entered by the user will be stored in the variable age. If the user fails to enter a number, zero will be assigned to age as a default value.
Figure 8.6 illustrates the versatility of programs that make use of input statements. The program asks a user to enter his or her name. Next, it stores the characters entered by the user into a text variable called firstName. The program then prints a greeting using the contents of firstName along with some additional text strings.
Looking at Figure 8.6 more closely, we see that the first thing this program does is to declare a text variable called firstName. Next, a text input statement is executed which will prompt the user to enter his or her name, and store the text string entered by that user into the variable firstName. If the user dismisses the input dialog without entering any text, the default value, an empty string “”, will be stored in firstName.
Program definition
| |||||||||||
| |||||||||||
| |||||||||||
| |||||||||||
| |||||||||||
| |||||||||||
| |||||||||||
|
Internal Variables
Program input/output behavior
Figure 8.6: A program that illustrates both input and output of text
It should be noted that while the input dialog box is displayed, the Watson JavaScript program is on “hold”. There is no set time limit on how long the program will wait for the user to enter his or her input. The program will “wake up” and continue with its execution when the user dismisses the input dialog window.
It is also important to recognize that the user is free to enter any sequence of characters he or she desires. However, since the message displayed on the screen asks for the user’s first name, that is what he or she will most likely enter – assuming the user is being cooperative and is capable of reading and understanding the input prompt. In Figure 8.6 the text string “Mike” was entered by the user and thus stored in firstName.
Next, the statement document.write(“Hello ”); prints
Hello _
on the screen. Since the statement is a “write”, as opposed to a “writeln”, the print position will remain on the same line as the string and be placed immediately following the last character of that string – a blank.
The next statement document.write(firstName); will print the current contents of firstName on the screen. Since this variable contains the text string “Mike”, those character are printed giving the following output
Hello Mike_
Note that the print position immediately follows the final character of the text string: “e”.
The last statement of the program:
document.writeln(“. Nice to meet you.”);
causes the output to become:
Since this statement is a “writeln”, it moves the print position to the next line of output. The program then terminates.
What we have just done is to walk, or trace, through a single run of the program of Figure 8.6. During this trace we assumed the user entered “Mike” at the input prompt. The power of input statements is that they allow programs to produce different outputs based on the inputs they are given. Thus, if the user had entered “Irene” instead of “Mike”, the program would have printed:
Hello Irene. Nice to meet you.
The flexibility and power that input statements give programming languages cannot be overstated. Without them the only way to get a program to change its output would be to modify the program code itself – something your typical user cannot be expected to do.
General-purpose programming languages, such as Watson JavaScript, allow human programmers to construct programs that do amazing things. When attempting to understand what a program does, however, it is vitally important that you always keep in mind that the computer does not comprehend the meaning of the character strings it manipulates or the significance of the calculations it performs.
For example, the program of Figure 8.6 is simply displaying strings of characters, storing user input, and echoing that input back to the screen along with some additional character strings. The computer has no clue what the text string “Please enter your first name.” means. For all it cares the string could have been “My hovercraft is full of eels.” or “qwerty uiop asdf ghjkl;” or any other text string for that matter. Its only concern is to copy the characters of the text string onto the display screen.
Only in the minds of human beings do the sequence of characters “Please enter your first name.” take on meaning. If this seems odd, try to remember that comprehension does not even occur in the minds of all humans, only those who are capable of reading and understanding written English. A four year old, for example, would not know how to respond to this prompt because he or she would be unable to read it. This is so despite the fact that if you were to ask the child his or her name, he or she could immediately respond and perhaps even type it out on the keyboard for you.
Figure 8.7 contains another program that demonstrates input and output. Unlike the program of Figure 8.6, which dealt with the input and output of text strings, this program illustrates the process on integers. The program begins by declaring two integer variables, one called firstNum and the other called secondNum. The program then prompts the user to enter a number. The input is captured and stored in firstNum. Next, the program prompts the user for another number and stores whatever the user enters in the variable secondNum. Finally, these numbers and their sum are printed – surrounded by appropriate character strings to form a meaningful sentence. A sample run of the program, on the numbers 15 and 10, is given in Figure 8.7 along with the actual program code.
You may be wondering what would happen if the user running this program were to enter a sequence of characters that did not form a valid number. For example, say the user attempted enter “cow” or “chicken” which are text strings, or even $37, which is not a valid number since it contains the special symbol “$”. If the system attempted to store these inputs into a numeric variable an error would result.
Program definition
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
| ||||||||||||||
|
Internal Variables
Program input/output behavior
Figure 8.7: A program that illustrates input and output of numeric data
The Watson JavaScript Lab has safeguards to prevent such errors from occurring. Input is only accepted from on-screen pop-up input dialogs. When a numeric value is to be read, the input dialog provides a numeric input pad for that purpose. Thus, the lab prevents the user from entering text when a number is required, since it is impossible to enter characters through the numeric entry pad. When a text string is to be read, the input dialog provides a type-in box.
In the “real world”, the safeguards of the Watson JavaScript Lab are often absent, so programmers must create robust programs that examine user input in order to verify that it is of the proper type, before processing that input. If the input is found to be in error, the program must take appropriate corrective action, such as rejecting the invalid input and requesting the user try again.
Exercises for Section 8.4
Show exactly what would be printed by the following Watson JavaScript program.
Write a Watson JavaScript program to produce the following output. Be sure to skip the blank line between the sentences.
Modify the program of Figure 8.6 so that it is capable of carrying on “conversations” such as the following, involving both a person’s name and age.
In the above program run, the user’s inputs, Mike and 45, are shown in italics. Your program should work with any name and age, so don’t “hard code” the values Mike and 45 into the program.