I'm trying to create a program that counts and displays the number of times a specified character appears in a file I made. The file name is Test.txt, and says "this is a file I made to test this program."
Here's what I've come up with, but it's not counting the letters right. Where did I go wrong?
//needed for scanner class
Scanner keyboard = new Scanner(System.in);
int charCount = 0;
//Get the filename.
System.out.println("Enter the filename:");
String filename = keyboard.nextLine();
//Open the file.
File file = new File("Test.txt");
// get users character
System.out.print("Please enter a character: ");
char userChar = keyboard.nextLine().charAt(0);
// tell the user what the program does
System.out.println("This program will return how many times" +
" the character you entered showed up in" +
" the file you entered.");
for(int i= 0;i<filename.length();i++)
{
if (filename.charAt(i) == userChar)
{
charCount++;
}
}
System.out.println("\nThe specified character " +"\"" + userChar +
"\" is inside the filename " + filename +
" " + charCount + " times.\n");
}
}