Java Reference
In-Depth Information
argument to System.out.print or System.out.println ; however, the line separator
output by System.out.println after it displays its argument is portable across operating
systems. Online Appendix I presents more details of formatting output with printf .
2.5 Another Application: Adding Integers
Our next application reads (or inputs) two integers (whole numbers, such as -22, 7, 0 and
1024) typed by a user at the keyboard, computes their sum and displays it. This program
must keep track of the numbers supplied by the user for the calculation later in the program.
Programs remember numbers and other data in the computer's memory and access that data
through program elements called variables . The program of Fig. 2.7 demonstrates these con-
cepts. In the sample output, we use bold text to identify the user's input (i.e., 45 and 72 ). As
in prior programs, Lines 1-2 state the figure number, filename and purpose of the program.
1
// Fig. 2.7: Addition.java
2
// Addition program that inputs two numbers then displays their sum.
3
4
5
import java.util.Scanner; // program uses class Scanner
public class Addition
6
{
7
// main method begins execution of Java application
8
public static void main(String[] args)
9
{
10
// create a Scanner to obtain input from the command window
Scanner input = new Scanner(System.in);
11
12
13
int number1; // first number to add
int number2; // second number to add
int sum; // sum of number1 and number2
14
15
16
17
System.out.print( "Enter first integer: " ); // prompt
18
number1 = input.nextInt(); // read first number from user
19
20
System.out.print( "Enter second integer: ") ; // prompt
21
number2 = input.nextInt(); // read second number from user
22
23
sum = number1 + number2; // add numbers, then store total in sum
24
25
System.out.printf( "Sum is %d%n" , sum); // display sum
26
} // end method main
27
} // end class Addition
Enter first integer: 45
Enter second integer: 72
Sum is 117
Fig. 2.7 | Addition program that inputs two numbers then displays their sum.
2.5.1 import Declarations
A great strength of Java is its rich set of predefined classes that you can reuse rather than
“reinventing the wheel.” These classes are grouped into packages named groups of related
 
 
 
Search WWH ::




Custom Search