Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The program below is suppose to open a file whose full pathname is provided by t

ID: 3627816 • Letter: T

Question

The program below is suppose to open a file whose full pathname is provided by the user in a keyboard entry. Then it is suppose to count the numbe rof words in the file, where any kind of whitespace is a word delimiter. The program is complete except a code fragment of several lines in the "try" block. Provide the missing code fragment. Use the anonymous File object as the "Scanner" argument when you instantiate the "fileIn" object. Of course, you can use the same Scanner - class "hasNext" and "next" methods for the "fileIn" object that you used before with the "stdIn" object when reading from the keyboard.

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

public class WordsnFile
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
Scanner filein;
int numWords = 0;

try
{
<code goes here>
}//end try
catch (FileNotFoundException e)
{
System.out.println("Invalid Filename.");
}
catch (Exception e)
{
System.out.println("Error reading from the file.");
}
}//end main
}//end WordsInFile class


Sample Output:

Enter full pathname of file:
e:/myJava/problems/chapter15/family.txt
Number of words = 63

Explanation / Answer

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

public class WordsInFile
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
Scanner fileIn;
int numWords = 0;

try
{
// codes goes here.
System.out.print("Enter full pathname of file: ");
fileIn = new Scanner(new FileReader(stdIn.nextLine()));

while (fileIn.hasNextLine())
{
String file = fileIn.next();
numWords++;
}

System.out.println("Number of words = " + numWords);

}

catch(FileNotFoundException e)
{
System.out.println("Invalid Filename");
}
catch(Exception e)
{
System.out.println("Error reading from the file.");
}
}//end of main
}//end of class