Complete Program

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:

Yes.

Complete Program

The complete program is given below.

import java.io.*;
import java.util.Scanner;

class TestGroupsSentinel
{
  public static void main ( String[] args ) throws IOException
  {
    int value;     // the value of the current integer
    
    // Prompt for and open the input file   
    Scanner user = new Scanner( System.in );
    System.out.print("File name? ");
    String fileName = user.next().trim();
    Scanner scan = new Scanner( new File(fileName) );  

    // 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" );
  
    // Group "B" 
    int sumB = 0;   // the sum of scores for group "B"
    int countB = 0;      // initialize count

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

    if ( countB > 0 )
      System.out.println( "Group B average: " + ((double) sumB)/countB ); 
    else
      System.out.println( "Group B  has no students" );
  }
}

QUESTION 17:

Could the sentinel method be used for a group that contains no data?