Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java How to Program, Fourth Edition - Deitel H., Deitel P.pdf
Скачиваний:
58
Добавлен:
24.05.2014
Размер:
14.17 Mб
Скачать

Chapter 2

Introduction to Java Applications

69

Common Programming Error 2.9

Forgetting to call System.exit in an application that displays a graphical user interface prevents the program from terminating properly. This omission normally results in the command window preventing you from typing any other commands. Chapter 14 discusses in more detail the reason that System.exit is required in GUI-based applications.

2.5 Another Java Application: Adding Integers

Our next application inputs two integers (whole numbers, like –22, 7 and 1024) typed by a user at the keyboard, computes the sum of the values and displays the result. This program uses another predefined dialog box from class JOptionPane called an input dialog that allows the user to input a value for use in the program. The program also uses a message dialog to display the sum of the integers. Figure 2.9 shows the application and sample screen captures.

1 // Fig. 2.9: Addition.java

2 // An addition program.

3

4// Java extension packages

5

import javax.swing.JOptionPane; // import

class JOptionPane

6

 

 

7

public class Addition {

 

8

 

 

9

// main method begins execution of Java

application

10public static void main( String args[] )

11{

12

String firstNumber;

// first string entered by user

13

String secondNumber;

// second string entered by user

14

int number1;

// first number to add

15

int number2;

// second number to add

16

int sum;

// sum of number1 and number2

17

 

 

18// read in first number from user as a String

19firstNumber =

20

JOptionPane.showInputDialog( "Enter first integer" );

21

 

22// read in second number from user as a String

23secondNumber =

24

JOptionPane.showInputDialog( "Enter second integer" );

25

 

26// convert numbers from type String to type int

27number1 = Integer.parseInt( firstNumber );

28number2 = Integer.parseInt( secondNumber );

29

30// add the numbers

31sum = number1 + number2;

33// display the results

34JOptionPane.showMessageDialog(

35

null, "The sum is " + sum, "Results",

36

JOptionPane.PLAIN_MESSAGE );

 

 

Fig. 2.9

An addition program “in action” (part 1 of 2).

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

70

Introduction to Java Applications

Chapter 2

37

38 System.exit( 0 ); // terminate application

39

40 } // end method main

41

42 } // end class Addition

Fig. 2.9 An addition program “in action” (part 2 of 2).

Lines 1 and 2,

//Fig. 2.9: Addition.java

//An addition program.

are single-line comments stating the figure number, file name and purpose of the program. Line 4,

// Java extension packages

is a single-line comment specifying that the next line imports a class from the Java extension packages.

Line 5,

import javax.swing.JOptionPane; // import class JOptionPane

indicates that the compiler should load class JOptionPane for use in this application. As stated earlier, every Java program consists of at least one class definition. Line 7,

public class Addition {

begins the definition of class Addition. The file name for this public class must be

Addition.java.

Remember that all class definitions start with an opening left brace (at the end of line 7), {, and end with a closing right brace, } (in line 42).

As stated earlier, every application begins execution with method main (lines 10–40). The left brace (line 11) marks the beginning of main’s body and the corresponding right brace (line 36) marks the end of main’s body.

Lines 12–13,

String

firstNumber;

//

first string entered by user

String

secondNumber;

//

second string entered by user

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 2

Introduction to Java Applications

71

are declarations. The words firstNumber and secondNumber are the names of variables. A variable is a location in the computer’s memory where a value can be stored for use by a program. All variables must be declared with a name and a data type before they can be used in a program. This declaration specifies that the variables firstNumber and secondNumber are data of type String (located in package java.lang), which means that the variables will hold strings. A variable name can be any valid identifier. Like statements, declarations end with a semicolon (;). Notice the single-line comments at the end of each line. This use and placement of the comments is a common practice used by programmers to indicate the purpose of each variable in the program.

Good Programming Practice 2.12

Choosing meaningful variable names helps a program to be self-documenting (i.e., it be- comes easier to understand the program simply by reading it rather than by reading manuals or viewing an excessive number of comments).

Good Programming Practice 2.13

By convention, variable-name identifiers begin with a lowercase letter. As with class names, every word in the name after the first word should begin with a capital letter. For example, identifier firstNumber has a capital N in its second word, Number.

Good Programming Practice 2.14

Some programmers prefer to declare each variable on a separate line. This format allows for easy insertion of a descriptive comment next to each declaration.

Software Engineering Observation 2.2

Java automatically imports classes from package java.lang, such as class String. Therefore, import statements are not required for classes in package java.lang.

Declarations can be split over several lines, with each variable in the declaration separated by a comma (i.e., a comma-separated list of variable names). Several variables of the same type may be declared in one declaration or in multiple declarations. Lines 12–13 can also be written as follows:

String firstNumber,

//

first string entered by user

secondNumber;

//

second string entered by user

Lines 14–16,

int number1;

// first number to add

int

number2;

//

second number to add

int

sum;

//

sum of number1 and number2

declare that variables number1, number2 and sum are data of type int, which means that these variables will hold integer values (whole numbers such as 7, –11, 0 and 31,914). We will soon discuss the data types float and double, for specifying real numbers (numbers with decimal points, such as 3.4, 0.0 and –11.19), and variables of type char, for specifying character data. A char variable may hold only a single lowercase letter, a single uppercase letter, a single digit or a single special character (such as x, $, 7 and *) and escape sequences (such as the newline character, \n). Java is capable of representing characters from many other spoken languages. Types such as int, double and char are often called primitive data types, or built-in data types. Primitive-type names are keywords;

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

72

Introduction to Java Applications

Chapter 2

thus, they must appear in all lowercase letters. Chapter 4 summarizes the eight primitive types (boolean, char, byte, short, int, long, float and double).

Line 18 is a single-line comment indicating that the next statement reads the first number from the user. Lines 19–20,

firstNumber =

JOptionPane.showInputDialog( "Enter first integer" );

reads from the user a String representing the first of the two integers to add. Method JOptionPane.showInputDialog displays the input dialog in Fig. 2.10.

The argument to showInputDialog indicates what the user should type in the text field. This message is called a prompt, because it directs the user to take a specific action. The user types characters in the text field, and then clicks the OK button or presses the Enter key to return the string to the program. (If you type and nothing appears in the text field, position the mouse pointer in the text field and click the left mouse button to activate the text field.) Unfortunately, Java does not provide a simple form of input that is analogous to displaying output in the command window with System.out’s method print and println. For this reason, we normally receive input from a user through a GUI component (an input dialog box in this program).

Technically, the user can type anything in the text field of the input. Our program assumes that the user follows directions and enters a valid integer value. In this program, if the user either types a noninteger value or clicks the Cancel button in the input dialog, a runtime logic error will occur. Chapter 14, Exception Handling, discusses how to make your programs more robust by enabling them to handle such errors. This is also known as making your program fault tolerant.

The result of JOptionPane method showInputDialog (a String containing the characters typed by the user) is given to variable firstNumber by using the assignment operator, =. The statement (lines 19–20) is read as “firstNumber gets the value of JOptionPane.showInputDialog( "Enter first integer" ).” The = operator is called a binary operator, because it has two operands: firstNumber and the result of the expression JOptionPane.showInputDialog( "Enter first integer" ). This whole statement is called an assignment statement, because it assigns a value to a variable. The expression to the right side of the assignment operator, =, is always evaluated first. In this case, the program calls method showInputDialog, and the value input by the user is assigned to firstNumber.

 

Prompt to the user.

When the user clicks OK,

 

showInputDialog

Text field in which the

returns the 45 typed by

user types a value.

the user to the program

 

as a String. The

 

program must convert

 

the String to an

 

integer.

 

Fig. 2.10 Input dialog box.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 2

Introduction to Java Applications

73

Line 22 is a single-line comment indicating that the next statement reads the second number from the user.

Lines 23–24,

secondNumber =

JOptionPane.showInputDialog( "Enter second integer" );

display an input dialog in which the user types a String representing the second of the two integers to add.

Lines 27–28,

number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber );

convert the two Strings input by the user to int values that the program can use in a calculation. Method Integer.parseInt (a static method of class Integer) converts its String argument to an integer. Class Integer is defined in package java.lang. Line 27 assigns the int (integer) value that Integer.parseInt returns to variable number1. Line 28 assigns the int (integer) value that Integer.parseInt returns to variable number2.

Line 31,

sum = number1 + number2;

is an assignment statement that calculates the sum of the variables number1 and number2 and assigns the result to variable sum by using the assignment operator, =. The statement is read as, “sum gets the value of number1 + number2.” Most calculations are performed in assignment statements. When the program encounters the addition operation, it uses the values stored in the variables number1 and number2 to perform the calculation. In the preceding statement, the addition operator is a binary operator: its two operands are number1 and number2.

Good Programming Practice 2.15

Place spaces on either side of a binary operator. This format makes the operator stand out and makes the program more readable.

After the calculation has been performed, lines 34–36,

JOptionPane.showMessageDialog(

null, "The sum is " + sum, "Results",

JOptionPane.PLAIN_MESSAGE );

use method JOptionPane.showMessageDialog to display the result of the addition. This new version of JOptionPane method showMessageDialog requires four arguments. As in Fig. 2.6, the null first argument indicates that the message dialog will appear in the center of the screen. The second argument is the message to display. In this case, the second argument is the expression

"The sum is " + sum

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

74

Introduction to Java Applications

Chapter 2

which uses the operator + to “add” a String (the literal "The sum is ") and the value of variable sum (the int variable containing the result of the addition on line 31). Java has a version of the + operator for string concatenation that concatenates a String and a value of another data type (including another String); the result of this operation is a new (and normally longer) String. If we assume that sum contains the integer value 117, the expression evaluates as follows:

1.Java determines that the two operands of the + operator (the string "The sum is " and the integer sum) are of different types and one of them is a String.

2.Java converts sum to a String.

3.Java appends the String representation of sum to the end of "The sum is ", resulting in the String "The sum is 117".

Method showMessageDialog displays the resulting String in the dialog box. Note that the automatic conversion of integer sum occurs only because the addition operation concatenates the String literal "The sum is " and sum. Also, note that the space between is and 117 is part of the string "The sum is ". String concatenation is discussed in detail in Chapter 10, “Strings and Characters.”

Common Programming Error 2.10

Confusing the + operator used for string concatenation with the + operator used for addition can lead to strange results. For example, assuming that integer variable y has the value 5, the expression "y + 2 = " + y + 2 results in the string "y + 2 = 52", not "y + 2 = 7", because first the value of y is concatenated with the string "y + 2 = ", and then the value 2 is concatenated with the new larger string "y + 2 = 5". The expression "y + 2 = " + (y + 2) produces the desired result.

The third and fourth arguments of method showMessageDialog in Fig. 2.9 represent the string that should appear in the dialog box’s title bar and the dialog box type, respectively. The fourth argument—JOptionPane.PLAIN_MESSAGE—is a value indicating the type of message dialog to display. This type of message dialog does not display an icon to the left of the message. Figure 2.11 illustrates the second and third arguments and shows that there is no icon in the window.

The message dialog types are shown in Fig. 2.12. All message dialog types except PLAIN_MESSAGE dialogs display an icon to the user indicating the type of message.

Argument 3: The title bar string

Argument 2: The message to display

The user clicks OK to dismiss the dialog.

Fig. 2.11 Message dialog box customized with the four-argument version of method showMessageDialog.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 2

Introduction to Java Applications

75

 

 

 

 

Message dialog type

Icon

Description

 

 

 

 

JOptionPane.ERROR_MESSAGE

 

Displays a dialog that indicates an error

 

 

to the user.

 

JOptionPane.INFORMATION_MESSAGE

 

Displays a dialog with an informational

 

 

message to the user. The user can sim-

 

 

ply dismiss the dialog.

 

JOptionPane.WARNING_MESSAGE

 

Displays a dialog that warns the user of

 

 

a potential problem.

 

JOptionPane.QUESTION_MESSAGE

 

Displays a dialog that poses a question

 

 

to the user. This dialog normally

 

 

 

requires a response, such as clicking on

 

 

a Yes or a No button.

 

JOptionPane.PLAIN_MESSAGE

no icon

Displays a dialog that simply contains a

 

 

message, with no icon.

 

Fig. 2.12 JOptionPane constants for message dialogs.

2.6 Memory Concepts

Variable names such as number1, number2 and sum actually correspond to locations in the computer's memory. Every variable has a name, a type, a size and a value.

In the addition program of Fig. 2.9, when the statement

number1 = Integer.parseInt( firstNumber );

executes, the string previously typed by the user in the input dialog and stored in firstNumber is converted to an int and placed into a memory location to which the name number1 has been assigned by the compiler. Suppose that the user enters the string 45 as the value for firstNumber. The program converts firstNumber to an int, and the computer places that integer value, 45, into location number1, as shown in Fig. 2.13.

Whenever a value is placed in a memory location, the value replaces the previous value in that location. The previous value is destroyed (i.e., lost).

When the statement

number2 = Integer.parseInt( secondNumber );

executes, suppose that the user enters the string 72 as the value for secondNumber. The program converts secondNumber to an int, and the computer places that integer value, 72, into location number2. The memory appears as shown in Fig. 2.14.

number1 45

Fig. 2.13 Memory location showing the name and value of variable number1.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

76

Introduction to Java Applications

Chapter 2

number1 45

number2 72

Fig. 2.14 Memory locations after storing values for number1 and number2.

After the program of Fig. 2.9 obtains values for number1 and number2, it adds the values and places the sum into variable sum. The statement

sum = number1 + number2;

performs the addition and also replaces sum’s previous value. After sum has been calculated, memory appears as shown in Fig. 2.15. Note that the values of number1 and number2 appear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation. Thus, when a value is read from a memory location, the process is nondestructive.

2.7 Arithmetic

Most programs perform arithmetic calculations. The arithmetic operators are summarized in Fig. 2.16. Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication, and the percent sign (%) is the modulus operator, which is discussed shortly. The arithmetic operators in Fig. 2.16 are binary operators, because they each operate on two operands. For example, the expression sum + value contains the binary operator + and the two operands sum and value.

Integer division yields an integer quotient; for example, the expression 7 / 4 evaluates to 1, and the expression 17 / 5 evaluates to 3. Note that any fractional part in integer division is simply discarded (i.e., truncated)—no rounding occurs. Java provides the modulus operator, %, that yields the remainder after integer division. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3, and 17 % 5 yields 2. This operator is most commonly used with integer operands, but also can be used with other arithmetic types. In later chapters, we consider many interesting applications of the modulus operator, such as determining if one number is a multiple of another. There is no arithmetic operator for exponentiation in Java. Chapter 5 shows how to perform exponentiation in Java. [Note: The modulus operator can be used with both integer and floating-point numbers.]

number1 45

number2 72

sum 117

Fig. 2.15 Memory locations after calculating the sum of number1 and number2.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 2

 

Introduction to Java Applications

77

 

 

 

 

 

Java operation

Arithmetic operator

Algebraic expression

Java expression

 

 

 

 

 

 

 

 

Addition

+

f + 7

 

 

f + 7

 

Subtraction

p c

 

 

p - c

 

Multiplication

*

bm

 

 

b * m

 

Division

/

x / y or

x

or x y

x / y

 

 

 

--

 

 

 

 

 

y

 

 

 

Modulus

%

r mod s

 

 

r % s

 

Fig. 2.16 Arithmetic operators.

Arithmetic expressions in Java must be written in straight-line form to facilitate entering programs into the computer. Thus, expressions such as “a divided by b” must be written as a / b, so that all constants, variables and operators appear in a straight line. The following algebraic notation is generally not acceptable to compilers:

a

--

b

Parentheses are used in Java expressions in the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write

a * ( b + c )

Java applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra:

1.Operators in expressions contained within pairs of parentheses are evaluated first. Thus, parentheses may be used to force the order of evaluation to occur in any sequence desired by the programmer. Parentheses are at the highest level of precedence. In cases of nested or embedded parentheses, the operators in the innermost pair of parentheses are applied first.

2.Multiplication, division and modulus operations are applied next. If an expression contains several multiplication, division or modulus operations, the operators are applied from left to right. Multiplication, division and modulus operators have the same level of precedence.

3.Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence.

The rules of operator precedence enable Java to apply operators in the correct order. When we say that operators are applied from left to right, we are referring to the associativity of the operators. We will see that some operators associate from right to left. Figure 2.17 summarizes these rules of operator precedence. This table will be expanded as additional Java operators are introduced. A complete precedence chart is included in Appendix C.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

78

Introduction to Java Applications

Chapter 2

 

 

 

 

Operator(s)

Operation(s)

Order of evaluation (precedence)

 

 

 

 

 

( )

 

Parentheses

Evaluated first. If the parentheses are nested, the

 

 

 

expression in the innermost pair is evaluated first. If

 

 

 

there are several pairs of parentheses on the same

 

 

 

level (i.e., not nested), they are evaluated left to right.

*, / and %

Multiplication

Evaluated second. If there are several of this type of

 

 

Division

operator, they are evaluated from left to right.

 

 

Modulus

 

 

+ or -

Addition

Evaluated last. If there are several of this type of oper-

 

 

Subtraction

ator, they are evaluated from left to right.

 

Fig. 2.17 Precedence of arithmetic operators.

Now, let us consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its Java equivalent.

The following is an example of an arithmetic mean (average) of five terms:

a + b + c + d + e Algebra: m = ---------------------------------------

5

Java: m = ( a + b + c + d + e ) / 5;

The parentheses are required, because division has higher precedence than that of addition. The entire quantity ( a + b + c + d + e ) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates as

e a + b + c + d + -- 5

The following is an example of the equation of a straight line:

Algebra:

y = mx + b

Java:

y = m * x + b;

No parentheses are required. The multiplication operator is applied first, because multiplication has a higher precedence than that of addition. The assignment occurs last, because it has a lower precedence than that of multiplication and division.

The following example contains modulus (%), multiplication, division, addition and subtraction operations:

Algebra:

z = pr%q + w/x y

 

 

 

Java:

z =

p *

r %

q +

w /

x - y;

 

6

1

2

4

3

5

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01