Chapter 2 Introduction to Java Applications 73 Line (Make my own web site)
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, sumgets 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