I am writing a program that reads words in a text file, but I am getting an erro
ID: 3627889 • Letter: I
Question
I am writing a program that reads words in a text file, but I am getting an error when input the complete file path to the text file, family.txt. I have made sure the file is saved in the path and that the text file is not open in memory. I have also tried other text files too. This text file is actually the file created by the text book.
I have the following code that is supposed to count the number of words in a text file:
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
{
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);
}//end try
catch(FileNotFoundException e)
{
System.out.println("Invalid Filename");
}//end catch
catch(Exception e)
{
System.out.println("Error reading from the file.");
}//end catch
}//end of main
}//end of class
-----------------------------------------------------------------------------------------------------------
When I run the program; however, I get the following output:
The output should read:
Number of words = 63
---------------------------------------------------------------------------------------------------------------
Explanation / Answer
Well usually I put a txt file that is being read in the folder that the program is running in but if that is not possible... Maybe your program is being thrown off by the spaces in the folder with spaces in their name To test if this is the case just put your text file in C: and try running it then One solution, if that is the problem, is to add quotes around the field path Hope that helps
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.