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

Answer:

See below.


Problems with Sentinels

// 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" );

Notice how input of the next integer, and the testing of that integer, is done in the condition of the while statement:

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

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

(value = scan.nextInt())

This reads in an integer and assigns it to value. The entire 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.


QUESTION 16:

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