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

Answer:

Yes. The square of each integer will be printed.


User Names the File

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

class NamedFileInput
{
  public static void main (String[] args) throws IOException
  { 
    int num, square;    

    // this Scanner is used to read what the user enters
    Scanner user = new Scanner( System.in ); 
    String  fileName;

    System.out.print("File Name: ");
    fileName = user.nextLine().trim();
    File file = new File( fileName );     // create a File object

    // this Scanner is used to read from the file
    Scanner scan = new Scanner( file );      

    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 above program asks the user for the the name of the file. First a Scanner is set up to read from standard input:

Scanner user = new Scanner( System.in ); 
String  fileName;

Then the user is prompted and the file name is read in using this Scanner. The trim() method trims off spaces (if any) from both ends of the file name.

System.out.print("File Name: ");
fileName = user.nextLine().trim();

Then a Scanner object is constructed for the named disk file.

File file = new File( fileName ); 
Scanner scan = new Scanner( file );      

This might result in an IOException, so main() must declare throws IOException. After this, the program works as before.


QUESTION 10:

If the user enters a name of a file that does not exist, will the program end gracefully?