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

Answer:

Sure, the same way as with the name of the input file with Scanner

The following program (a revision of a previous example) prompts the user for both the names of the input file and the output file.


File Name from User Input

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

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

    // Scanner for user input
    Scanner user = new Scanner( System.in ); 
    String  inputFileName, outputFileName;

    // prepare the input file
    System.out.print("Input File Name: ");
    inputFileName = user.nextLine().trim();
    File input = new File( inputFileName );      
    Scanner scan = new Scanner( input );      

    // prepare the output file
    System.out.print("Output File Name: ");
    outputFileName = user.nextLine().trim();
    PrintWriter output = new PrintWriter( outputFileName );      

    // processing loop
    while( scan.hasNextInt() )    
    {
      num = scan.nextInt();
      square = num * num ;      
      output.println("The square of " + num + " is " + square);
    }

    // close the output file
    output.close();
  }
}

This program can be used as the basis for many others. Several of the programming exercises can be done by copying this program and making small changes to the processing loop.


QUESTION 14:

How could you create a program that adds up all the integers in a file of text integers?