User Names the File

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:

No.

User Names the File

It would be nice to allow the user to give the name of the file from which data will be read. The following program does that:

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);
    }
  }
}

First a Scanner is set up to read what the user types:

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 from both ends of the file name.

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

Then a second Scanner object is constructed and connected to the named disk file. This might result in an IOException, so main() must declare throws IOException.

File file = new File( fileName );     // create a File object
Scanner scan = new Scanner( file );      

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?