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




Most files contain a great deal of data. Practical programs must process this data using a loop of some sort. Here is a program that reads a text file that contains many integers and writes the square of each one. The loop reads integers from the file one by one until the end of file is reached or non-integer input is encountered.

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

class ManySquares
  public static void main (String[] args) throws IOException
    File    file = new File("myData.txt");   // create a File object
    Scanner scan = new Scanner( file );      // connect a Scanner to the file
    int num, square;      

    while( scan.hasNextInt() )   // is there more data to process? 
      num = scan.nextInt();
      square = num * num ;      
      System.out.println("The square of " + num + " is " + square);

The hasNextInt() method returns true if the next set of characters in the input stream can be read in as an int. If they can't be read as an int, or if the end of the file has been reached, then it returns false.


Does this program require a specific number of integers in the input file?