Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file.
mport java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileRead {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the file name or type QUIT to exit:");
String filename = keyboard.nextLine();
if (filename.equalsIgnoreCase("Quit"))
return;
File myFile = new File(filename);
while (!myFile.exists()) {
System.out.println("File: " + filename + " does not exist.");
System.out.println("Please enter the file name again or type QUIT to exit:");
filename = keyboard.nextLine();
if (filename.equalsIgnoreCase("Quit")) {
return;
}
myFile = new File(filename);
}
Scanner inputFile = new Scanner(myFile);
int lines = 0;
while (inputFile.hasNext()) {
String str = inputFile.nextLine();
lines++;
System.out.println(lines + ": " + str);
}
inputFile.close();
}
}
Test Case 1
QUITENTER
Test Case 2
badfilename.txtENTER
File: badfilename.txt does not exist.\n
Please enter the file name again or type QUIT to exit:\n
quitENTER
Test Case 3
input.txtENTER
Please enter a character: \n
oENTER
Letter 'o' occurs 4 times in the file 'input.txt'.\n
Test Case 4
letters.txtENTER
Please enter a character: \n
aENTER
Letter 'a' occurs 82 times in the file 'letters.txt'.\n

Trending now
This is a popular solution!
Step by step
Solved in 4 steps with 2 images









