I have to write a program that asks the user to enter a filename, and also a specific character that they want to be read. The program will display the amount of times that it is in the file.
An example of this would be:
Enter file: t.txt
Enter character to read throughout file: a
here is what i have so far. Everything so far seems to be right, but I am having trouble declaring the char value for this. Any help would be very appreciated.
An example of this would be:
Enter file: t.txt
Enter character to read throughout file: a
here is what i have so far. Everything so far seems to be right, but I am having trouble declaring the char value for this. Any help would be very appreciated.
import java.util.Scanner;
import java.io.*;
public class FileLetterCounter {
public static void main(String[] args) throws IOException {
// declare variables
String fileName;
int times = 0;
String letter;
char character;
Scanner nameScan = new Scanner(System.in);
// getting the name of the file.
System.out.print("Enter the name of the file: ");
fileName = nameScan.nextLine();
// getting the letter the file will read
System.out.print("Enter the letter for the file to search: ");
letter = nameScan.nextLine();
// open the file
File file = new File(fileName);
if(file.exists()) {
Scanner fileScan = new Scanner(file);
// reading the file
while(fileScan.hasNext()) {
for(int i = 0; i < letter.length(); i++) {
if(letter.charAt(i) == character)
times++;
else
times = 0;
}
}
// close file
fileScan.close();
// display information
System.out.println("The file contains \'" + letter + "\' " + times + " time(s).");
}
else {
System.out.println("Error 332: Cannot find file.");
System.exit(0);
}
}
}