0

I am writing a program using J2ME and my goal is to count how many times each character appears in a string.

I am not very good at java so the way i see i should do this is create 2 arrays.
First array is used to hold characters. Second array is used to keep count

The program goes through checks if the first character of the string is in the first array. If it isn't, then put it in the first position in the array and add 1 to its count in the second array. This loops through until every character has been counted.

I feel this method seems kinda long winded so i was wondering if someone could offer me a better way of doing it?

I have searched and people have said use hash maps. I dont know what they are but it looks like they are not available in J2ME anyway.

2
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by lethal.b
1

Remember Java chars are numeric - ordinary characters correspond to integer values under 128. If you have an array of 127 ints you can use a char as the index to access an element of the array and increment it...

0

thanks for the reply,

So you mean i wouldn't need my first array then? Is the numeric value of the char the decimal for it in the ascii table?

Also if using the numeric value of the chars can it be used on the extended characters in the ascii table as well?

1

Yes, you only need one array.
Yes, the numeric value of the char the decimal for it in the ascii table.
Not exactly ... Java uses 16 bit UniCode to store characters, and these are only the same as ASCII for codes up to 127. ASCII extended characters are basically irrelevant in Java as UniCode handles all such symbols far better.
Having said all that, you don't really need to know the decimal equivalents, just use chars and they will work as both letters and numeric values as if by magic, eg

for (char c = 'a'; c <= 'z'; c++) System.out.print(c);
or
array++;

0

ah i understand it now. Thanks for thelp. I guess i can mark this as solved

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.