// Need this import for reading data:
import java.io.*;

// counting the number of occurrences of 'a'
// in the input string
public class CharCounting {

    public static void main (String [] args) throws IOException {
	// Create a buffered reader
	BufferedReader in = new BufferedReader(
			new InputStreamReader(System.in));
	// string for storing a line of input
	String line;

	// prompt the user:
	System.out.print("Please say something: ");
	// read the line:
	line = in.readLine();
	// set up the counter:
	int counter = 0;
	// store the length of the string:
	int len = line.length();

	// go through each character, count 'a':
	for (int i = 0; i < len; ++i) {
	    if (line.charAt(i) == 'a') 
	System.out.println("The string has " + counter + " letters a");


This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.