Java Reference
In-Depth Information
public static void main(String[] args)
{
int limit;
//store the number of items
//in the list
int number;
//variable to store the number
int sum;
//variable to store the sum
int counter;
//loop control variable
System.out.print("Line 1: Enter the number of "
+ "integers in the list: ");
//Line 1
limit = console.nextInt();
//Line 2
System.out.println();
//Line 3
sum = 0;
//Line 4
counter = 0;
//Line 5
System.out.println("Line 6: Enter " + limit
+ " integers.");
//Line 6
while (counter < limit)
//Line 7
{
number = console.nextInt();
//Line 8
sum = sum + number;
//Line 9
counter++;
//Line 10
}
System.out.printf("Line 11: The sum of the %d " +
"numbers = %d%n", limit, sum);
//Line 11
if (counter != 0) //Line 12
System.out.printf("Line 13: The average = %d%n",
(sum / counter));
//Line 13
else
//Line 14
System.out.println("Line 15: No input.");
//Line 15
}
}
Sample Run: (In this sample run, the user input is shaded).
Line 1: Enter the number of integers in the list: 12
Line 6: Enter 12 integers.
8 9 2 3 90 38 56 8 23 89 7 2
Line 11: The sum of the 12 numbers = 335
Line 13: The average = 27
The preceding program works as follows: The statement in Line 1 prompts the user to
input the data for processing. The statement in Line 2 reads the next input and stores it in
the variable limit . The value of limit indicates the number of items to be read. The
statements in Lines 4 and 5 initialize the variables sum and counter to 0 . The while
statement in Line 7 checks the value of counter to determine how many items have
been read. If counter is less than limit , the while loop proceeds for the next iteration.
 
Search WWH ::




Custom Search