Write a program in Java that asks the user for an input stan
Write a program in Java that asks the user for an input standard txt file name and prints
the number of characters, words, and lines in that file.
Note: Use exception handling to detect improper inputs.
Java program. Please, the program can compile and run. Thanks!!
Solution
FileRead.java
import java.io.File;
import java.util.Scanner;
public class FileRead{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(\"Enter the input file name\");
String inputFile = input.next();
System.out.println(\"-------------------------------\");
getinput2(inputFile);
}
public static void getinput2(String fileName){
String input;
Scanner fileInput = null;
int linecount = 0, wordcount = 0, charcount = 0;
File inFile = new File(fileName);
try{
fileInput = new Scanner(inFile);
while(fileInput.hasNext()){
input = fileInput.nextLine();
String words[] = input.split(\" \");
for(int i=0; i<input.length(); i++){
if(Character.isLetter(input.charAt(i)))
charcount++;
}
wordcount = wordcount + words.length;
linecount++;
}
System.out.println(\"Number of lines : \"+linecount);
System.out.println(\"Number of Words : \"+wordcount);
System.out.println(\"Number of characters : \"+charcount);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Output:
Enter the input file name
D:\\\\input.txt
-------------------------------
Number of lines : 4
Number of Words : 22
Number of characters : 84
input.txt
Mary had a little lamb
Its fleece was white as snow
And everywhere that Mary went
The lamb was sure to go.

