go to previous page   go to home page   go to next page highlighting

Answer:

See below.


Programming Trick

// Group "A"
int sumA = 0;      // the sum of scores for group "A"
int countA = 0;    // initialize the group A count

while ( (value = scan.nextInt()) != -1 )
{
  sumA   = sumA + value ; // add to the sum
  countA = countA + 1;    // increment the count
}

if ( countA > 0 )
  System.out.println( "Group A average: " + ((double) sumA)/countA ); 
else
  System.out.println( "Group A  has no students" );

The condition part of the while statement does two things. It reads the next integer, and tests that it is not the sentinel.

while ( (value = scan.nextInt()) != -1 )

The part inside the inner-most parentheses is done first.

(value = scan.nextInt())

This reads in an integer and assigns it to value. The expression has the value of that integer. If a -1 was read, then the expression has the value -1.

Next, the value of the expression is compared to -1:

while ( expression != -1 )

If a -1 was just read, the relational expression will evaluate to false and the while loop will stop.

All this may seem needlessly complicated, but it is a convenient and frequently used programming trick.


QUESTION 16:

Will the loop continue if any value other than minus one was read?


go to previous page   go to home page   go to next page