0

I need to count the amount of a specific character in a file. The user will specify the char I just need to check how many chars there is in a file.

package assignmentoneqone;
import java.util.Scanner;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;

/**
 *
 * @author Hannes
 */
public class AssignmentOneQOne {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner kb = new Scanner(System.in);

        String fileLoc;
        String userChar;

        //User specify the file and character

        System.out.println("Enter the file name");
        fileLoc = kb.nextLine();
        System.out.println("Enter a character");
        userChar = kb.nextLine();

        File file = new File(fileLoc);
        try
        {
        FileReader fw = new FileReader(file);

This is where I should do my search for characters.

        }
        catch(IOException e)
                {
                System.out.println("The file does not exist.");
                }                 
    }
}
user2980509
  • 132
  • 1
  • 3
  • 12

4 Answers4

0

Using the beautiful guava for this... (if that's an option)

        int result = CharMatcher.is('t').countIn("test"); //of course for each line instead of 'test'
    System.out.println(result);
Eugene
  • 117,005
  • 15
  • 201
  • 306
0

Open your file, read line for line in a while loop (google how).

in your while loop you can count a char like:

int counter = 0;
char[] arr = line.toCharArray();

for (char c: arr){
    if (c == '<your char>' || c== '<YOUR CHAR UPPERCASE >')
      counter++;
}
VonSchnauzer
  • 912
  • 11
  • 17
  • `line` is what you read from your file. Like I said: read line for line from your text file in your while loop. http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java – VonSchnauzer Mar 10 '14 at 11:50
0
        file FileReader fw = new FileReader(file);
        int a = 0;
        int charCount = 0;
        while(( a = fw.read())!= -1)
        {
            byte b = (byte) a;
            if(b == 32 || b == 10) // Ascii value of space and enter
            {
                continue;
            }
            charCount++;
        }
        System.out.println("The character count is "+charCount);
Kick
  • 4,823
  • 3
  • 22
  • 29
0

If you're looking for a oneliner:

System.out.println(myString.replaceAll("[^a]+", "").length());

Note: may not be the speediest.

nablex
  • 4,635
  • 4
  • 36
  • 51