created: 3/23/2006


Fill in the Blanks

Instructions:   Each question has something left out. A button represents the missing word(s). Think of the word or phrase that completes the sentence, then click on the buttons to see if you are correct.


1.   One technique of file input is "while not end of file". Complete the following so all the integers in the file dataFile.txt are read in.

Scanner scan = new Scanner ( new   ( "dataFile.txt") );  

while ( )
{
  int value = scan. ;
   
  . . .
}

2.   Another technique where the first integer in a file says how may values follow. Complete the following so all the integers in the file headerFile.txt are read in.

Scanner scan = new Scanner ( new  File( "headerFile.txt" ) );
int limit = scan. ;
int count =  ;

while ( count  limit )
{
  int value = scan. ;
  count = count+1; 
  . . .
}

3.   An improvement to the previous program never attempts to read an integer unless it is certain that one is there to be read. Fill in the blanks so that errors in the input file so that the user is informed of errors.

Scanner scan = new Scanner ( new  File( "headerFile.txt" ) );
int limit = 0;

if ( scan.hasNextInt() )
{
  
  limit = scan. ;
  
  int count =  ;
  
  while ( count < limit && )
  {
    int value = scan.nextInt() ;
    count = count+1; 
    . . .
  }

  if ( count  limit )
    System.out.println("Too few input values."); 
}
else
  System.out.println("File has defective header");


4.   What is a disadvantage of using a sentinel-controlled loop for input?


5.   Is it wise to assume that input data will never be defective?


6.   Say that an input file consists of a number of lines. Each line consists of a word followed by a text integer. There are no header or sentinel in the input. What methods of Scanner are likely to be useful in reading this file? , and .



7.   The following program reads a text file. The file contains both integers and words, similar to the following:

ant 32 cat groundhog
dog 96 bat rat
avacado -12 eel 37
93 fox

The program is to scan the file for integers and write only the integers to standard output. Fill in the blanks so that it does this.

import java.util.Scanner;
import java.io.*;
class ScanForInts
{
  public static void main ( String[] args ) throws IOException

  {
    Scanner scan = new Scanner( new File( "mixedUpFile.data" ) );

    // continue while there are unread tokens
    while ( scan.  )
    {
      // if the next token is an integer get it and write it out
      if ( scan. )
      {
        int number = scan.;
        System.out.println( number );
      }
      else
        scan.;  // discard non-number token        
    }

  }
}

Notice that the hasNext..() methods do not consume any input and several of them can be used to determine what the next item of input is.



End of the Exercise. If you want to do it again, click on "Refresh" in your browser window. Click here to go back to the main menu.