Home > Computer Programming > Counting occurrences of a certain letter

Counting occurrences of a certain letter

January 14, 2013 Leave a comment Go to comments

This is some code that counts how many B’s there are in the words file.


package readfromfile;</pre>
import java.io.*;

public class ReadFromFile {
<pre>public static void main(String[] args) {
  String s = "";
  int i = 0;
  int count = 0;
  try {
    BufferedReader reader = new BufferedReader(new FileReader("c:\\words.txt"));
    i = reader.read();
    while (i != -1){
      s = new Character((char)i).toString(); // This converts the int to a String
      if (s.equals("B")){
        count = count + 1;
      }
      i = reader.read();
    }
    reader.close();
    System.out.println("The file contains " + count + " B characters.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s