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:

In the second catch{} block of the inner try{} block.

Complete Program

Here is the complete program to read in integers (and process them) until end of file.

import java.io.*;

class ReadIntEOF
{
  public static void main ( String[] args ) 
  {
    String fileName = "ints.dat" ;   long sum = 0;

    try
    {
      DataInputStream instr = 
        new DataInputStream(
          new BufferedInputStream(
            new FileInputStream( fileName ) ) );

      try
      {
        while ( true )
          sum += instr.readInt();
      }

      catch ( EOFException  eof )
      {
        System.out.println( "The sum is: " + sum );
        instr.close();
      }

      catch ( IOException iox )
      {
        System.out.println( "Problems reading " + fileName );
        instr.close(); 
      }
    }

    catch ( IOException iox )
    {
      System.out.println("IO Problems with " + fileName );
    }

  }
}

If you want to copy this program to a file and run it, you will need a binary file of integers. The "data translator" program from programming exercise one of the previous chapter can be used for that.

QUESTION 12:

If things go wrong, might this program try to close a file that failed to open?