Hi,

I'm trying to make a program which reads a text as an input and counts the letters as an output. For example, if my input is: "Hello, my name is Alan", I want my output to be:
A = 3, B = 0, C = 0, D = 0, E = 1,...., H = 1, I = 1,... L = 3, M = 2, N = 1, O = 1,.......
I think you understand what I mean.

This is what I've done so far:

import javax.swing.*;
import java.util.Random;

public class Letters
{
	private int max;
	private int[] freq;
	private char[] letter = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',     'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
	private Random generator;

	public Letters ()
	{
		generator = new Random();
		freq = new int[1000]; // Gave it some random elements, I guess elements is 27? (0-26)
	}

	public void count()
	{
		String input = JOptionPane.showInputDialog("Type in a sentence you want to convert: ");
		int num = 0; //how many numbers which appears for letter..

		for(int i = 0; i < input.length(); i++)
		{
			char sign = input.charAt( i ); // To check my input..?

			for(int j = 0; j < freq.length; j++)
			{
				num++;
			}
		}
	}

	public void output()
	{
		JTextArea print = new JTextArea();
		print.setText("Number of letters: ");

		for(int i = 0; i < bokstaver.length; i++)
		{
			if( i % 5 == 0)
			print.append("\n");

		    print.append( (i + 1) + ": " + letter[i] + "\t");
		}

		JOptionPane.showMessageDialog( null, print );
	}
}

It doesn't work, if my input is: Hello, my output is: a = 1, b = 2, c = 3.... z = 27.
What I've done wrong? I have a class with my main which run this program btw.
And one last thing, I'm very new to Java, and I'm not so familiar with arrays/loops/etc yet, but I'm trying to learn!

If you look closely, the value you are getting is the counting order from a=1, b=2, ..., z=27 :)

You should formulate how to tackle the problem first. The way you do seems to be a bit off. Let say, you are counting frequency of ASCII character? Do you allow any other special character to be enter? Do you count them if they are entered? I know one thing that you must count each letter and ignore its case (i.e. A and a are the same and must be counted).

Why do you have a random number generator in there? What does it do to help you get the solution for your problem?

If your answer is to count only A-Z case-insensitive, then my question to you is how big an array of frequency would you need? :) Then, if a character is case-insensitive, should you convert the string to either lower or upper case first, so you will need to compare with only one type of case (either lower or upper case)? Also, when you iterate through each character in a string, how do you count it? :)

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.