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");
}
}

Hi there were several problems in your code.just copy the code below and run it. make sure the file name you pass to the program exist.
The fundamental problem in you progarm is you are not opening up the file that you input anywhere in the code. Hope this helps

import java.io.*;
import java.util.Scanner;

public class Test{
public static void main(String args[]) throws Exception{
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.
Reader fileReader = new FileReader(filename);

// 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=fileReader.read()) != -1;)
{
	if (i == userChar)
	{
		charCount++;
	}
}

System.out.println("\nThe specified character " +"\"" + userChar +
"\" is inside the filename " + filename +
" " + charCount + " times.\n");
}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.