Capítulo II: Carrera de Enfermería, Universidad Estatal Península de Santa
2.9 Tecnologías de la información y comunicación de la Carrera de
Learning to program by example is easier if you have more examples. Figure 2-2 shows a different kind of program that asks the user to enter two integers (which is simply the mathematical term for whole numbers without fractional parts), adds those integers together, and then displays the sum.
FIGURE 2-2 Program to add two integers
/*
* File: Add2Integers.java * ---
* This program adds two integers and prints their sum. */
import acm.program.*;
public class Add2Integers extends ConsoleProgram { public void run() {
println("This program adds two integers."); int n1 = readInt("Enter n1: ");
int n2 = readInt("Enter n2: "); int total = n1 + n2;
println("The total is " + total + "."); }
}
The program in Figure 2-2 introduces several new programming concepts that were not part of HelloProgram. First, Add2Integers is a different kind of program, as indicated by its header line:
public class Add2Integers extends ConsoleProgram
This program extends ConsoleProgram instead of GraphicsProgram, which means that it has access to a different set of facilities. The ConsoleProgram class is designed to support user interaction in a traditional text-based style. A ConsoleProgram can request input from the user and display information back as illustrated in the following diagram, which shows what you might see if you ran the Add2Integers program:
Add2Integers
This program adds two integers. Enter n1: 17
Enter n2: 25
The total is 42.
Diagrams that show the output that a program produces are called sample runs. Although it may be hard to see in this photocopied edition of the text, the input that the user types appears in blue, as it does on the display when you run this program. This convention makes it easy to tell which parts of a session are entered by the user and which parts are generated by the program.
If you take a holistic look of this program, I’m certain you could have told me what it did even before you knew what any of its statements really did. If nothing else, the
program comment and the first line of the run method are dead giveaways. But even without those signposts, most beginning programmers would have little trouble understanding the function of the code. Programs are typically easier to read than they are to write. Moreover, just as it is far easier to write a novel after having read a number of them, you will find that it is easier to write good programs if you take the time to read several well-designed programs and learn to emulate their structure and style. The meaning of a particular statement—much like unfamiliar words in a novel—often becomes clear either from the context or from simple common sense. Before going on to look at the explanations that follow, try taking a look at each line of Add2Integers and see how much sense you can make of it working from first principles alone.
The first line in the run method is
println("This program adds two integers.");
The println method—which is a contraction of “print line”—is used to display information on the console. The value in parentheses is called an argument and tells the println method what it should display. The double quotes surrounding the text
This program adds two integers.
do not appear in the output but are used by Java to indicate that the characters between the quotation marks are an instance of text data called a string. The effect of the println method is to display the entire argument string on the console and then to return to the beginning of the next line. Thus, if you make several println calls in succession, each string in the output will appear on a separate line.
Note that the purpose of the first line in this program is not to tell programmers reading the code what the program does; that function is accomplished by the program comments at the beginning of the file. The first println statement is there to tell the user sitting at the computer what the program does. Most people who use computers today are not programmers, and it wouldn’t be reasonable to expect those users to look at the code for a program to determine what it did. The program itself has to make its purpose clear.
The next line of the run method looks like this: int n1 = readInt("Enter n1: ");
At a holistic level, the intent of the line is reasonably clear, given that everything you can see suggests that it must be reading the first integer value. If you adopt a reductionistic perspective, however, this line of code introduces several new concepts. Of these, the most important is that of a variable, which is easiest to think of as a placeholder for some piece of data whose value is unknown when the program is written. When you write a program to add two integers, you don’t yet know what integers the user will want to add. The user will enter those integers when the program runs. So that you can refer to these as-yet-unspecified values in your program, you create a variable to hold each value you need to remember, give it a name, and then use its name whenever you want to refer to the value it contains. Variable names are usually chosen so that programmers who read the program in the future can easily tell how each variable is used. In the Add2Integers program, the variables n1 and n2 represent the integers to be added, and the variable total represents the sum.
When you introduce a new variable in Java, you must declare that variable, which consists of making sure that the Java compiler knows the type of data that variable will
contain. In Java, the type used to store integer data is called int. A declaration of the form
int n1 = value ;
introduces a new integer variable called n1 whose value is given by whatever expression appears in the box labeled value. In this case, that expression is
readInt("Enter n1: ")
Just like the println example from the first line, this expression is an invocation of the readInt method in ConsoleProgram. The readInt method begins by displaying its argument on the console so that the user knows what is expected; this type of message is generally called a prompt. Unlike println, however, the readInt method does not return to the beginning of the next line but waits after the prompt for the user to type in an integer. When the user has finished typing in the integer and hits the Return or Enter key, that integer is then passed back as the result of the readInt method. In programming terminology, we say that readIntreturns the value the user typed.
When tracing through the operation of a program on paper, programmers often use box diagrams to indicate the values assigned to variables. If you look back at the sample run presented earlier in this section, you will see that the user entered the value 17 in response to the first input request. Thus, to illustrate that the assignment statement has stored the value 17 in the variable n1, you draw a box, name the box n1, and then indicate its value by writing a 17 inside the box, as follows:
n 17 1
The third line in the run method is almost exactly the same as the second and reads a value for the variable n2. If the user enters 25 in response to this prompt, you could update your box diagram to show the new variable, as follows:
n 17
1 n
25 2
The next line in the run method is int total = n1 + n2;
This statement declares the variable total and assigns it the value to the right of the equal sign, which is
n1 + n2
This piece of the code is an example of an essential programming construct called an
expression that represents the result of computation. The structure of expressions is defined more formally in Chapter 3, but it is often easy to understand what a Java expression means given that they look very much like expressions in traditional mathematics.
In Add2Integers, the goal is to add the values stored in the variables n1 and n2. To do so, you use the + operator, which you’ve understood since elementary-school arithmetic. To keep track of the result, you need to store it in some variable, and this statement introduces total for precisely this purpose.
The final statement in the run method is
println("The total is " + total + ".");
which accomplishes the task of displaying the computed result. For the most part, this statement looks like the first statement in the program, which is also a call to the println method. This time, however, there’s a new twist. Instead of taking a single string argument, this statement passes to println the argument value
"The total is " + total + "."
Just like the n1+n2 expression from the previous statement, this value is given by an expression involving the + operator. In this statement, however, at least some of the values to which + is applied are string data rather than the numeric data on which addition is defined. In Java, applying the + operator to string data reinterprets that operator to mean adding the strings together end to end to combine their characters. This operation is called concatenation. If there are any parts of the expression that are not strings, Java converts them into their standard string representation before applying the concatenation operator. The effect of this last println statement is to display the value of total after adding on the surrounding text. You can see the effect of this statement in the sample run.
Although Add2Integers is set up to work only with integers, Java is capable of working with many other types of data. You could, for example, change this program so that it added two real numbers simply by changing the types of the variables and the names of the input methods, as shown in Figure 2-3.
FIGURE 2-3 Program to add two double-precision numbers
/*
* File: Add2Doubles.java * ---
* This program adds two double-precision floating-point numbers * and prints their sum.
*/
import acm.program.*;
public class Add2Doubles extends ConsoleProgram { public void run() {
println("This program adds two numbers."); double n1 = readDouble("Enter n1: "); double n2 = readDouble("Enter n2: "); double total = n1 + n2;
println("The total is " + total + "."); }
In most programming languages, numbers that include a decimal fraction are called floating-point numbers, which are used to approximate real numbers in mathematics. The most common type of floating-point number in Java is the type double, which is short for double-precision floating-point. If you need to store floating-point values in a program, you must declare variables of type double, just as you previously had to declare variables of type int to write Add2Integers. The only other change in the program is that the user input is obtained by calling readDouble instead of readInt. The basic pattern of the program is unchanged.