Problems with Sentinels

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

See below.

Problems with Sentinels

Here is part A of the program with the blanks filled.

    // 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?