4

so I have an assignment about array. It is asked to use Scanner to read through text files and record the occurrences of each alphabet and store them in a table.

For example:

public class something {

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();

public void displayTable () {
        for (int i = 0; i < alphabet.length; i++) {
            System.out.println(alphabet[i] + ":  " + count);
        }
    }

I don't know how to construct the method to store the occurrences of each alphabet.

It is supposed to be like:

public void countOccurrences (Scanner file) {
     //code to be written here
}

If the text file only has a line and the line is :

Hello World

The method would ignore any integers or symbols and only output char that appeared in the table.

d: 1
e: 1
h: 1
l: 3
o: 2
r: 1
w: 1

I can't figure this out myself and any help is greatly appreciated!

Thanks, Shy

2 Answers2

2

Simply use Map. Read inline comments for more info.

Map<Character, Integer> treeMap = new TreeMap<Character, Integer>();
// initialize with default value that is zero for all the characters
for (char i = 'a'; i <= 'z'; i++) {
    treeMap.put(i, 0);
}

char[] alphabet = "Hello World".toCharArray();

for (int i = 0; i < alphabet.length; i++) {
    // make it lower case
    char ch = Character.toLowerCase(alphabet[i]);
    // just get the value and update it by one
    // check for characters only
    if (treeMap.containsKey(ch)) {
        treeMap.put(ch, treeMap.get(ch) + 1);
    }
}

// print the count
for (char key : treeMap.keySet()) {
    int count = treeMap.get(key);
    if (count > 0) {
        System.out.println(key + ":" + treeMap.get(key));
    }
}

output for Hello World ignore case

d:1
e:1
h:1
l:3
o:2
r:1
w:1

Read file line by line. Iterate all the character of the line and update the occurrence in the Map.

Braj
  • 46,415
  • 5
  • 60
  • 76
  • Hi, thanks for the quick response however I haven't learn these yet (map/treeMap) And I can't understand them, I am in a basic java introduction class so so far I only learned while/for loops, nested loops, if/else, classes construction and arrays. Is there other way to do this? –  May 18 '14 at 20:17
  • Its a key value pair. – Braj May 18 '14 at 20:18
0

Note that I assumed that the only possible letters are from a to z.

So what you can do is build an array that will contains 26 entries (each entry which will correspond to the number of occurences of for the corresponding character).

Now the thing to get is a mapping letter -> index with 'a' -> 0, 'b' -> 1 to 'z' -> 25.

How would you get the mapping?

The trick is that characters are a kind of integer, as each character as actually an integer value associated (through the Unicode chart) (a is 97, b is 98 and so on).

In this case valueOfChar - 'a' will do the mapping and it's the key thing to understand. This will ensure that the value returned by this operation is between 0 and 25 because you know that each character will return a character between a and z (converting the input in lower case).

So to summarize :

  1. For each line, split it by spaces.
  2. Loop through each word to get the characters
  3. Put the character in lower case (if you put all the line in lower case, this step is useless)
  4. Update the corresponding number of occurences in the array for this character using the above mapping

Here's a little example to show how the mapping works:

public class Test { 
    static final int[]  occurences = new int[26];
    public static void main(String args[]){
        String test = "helloworld";
        for(char c : test.toCharArray()){
            occurences[c - 'a']++;
        }
        for(char c = 'a'; c <= 'z'; c++){
            if(occurences[c - 'a'] != 0){
                System.out.println(c + " => "+occurences[c - 'a']);
            }
        }
    }
}

Output:

d => 1
e => 1
h => 1
l => 3
o => 2
r => 1
w => 1
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • Thank you very much! I was surprised that you guessed right about only lowercase alphabets are allowed (uppercase need to be converted, I use file.next().toLowerCase() to do that, not sure if it works tho) –  May 18 '14 at 20:21
  • @user3650523 Yes there are several ways to do this! – Alexis C. May 18 '14 at 20:26
  • First of all thank you for the explanation and quick response. Is there any way that I can talk to you faster? Like chat or something? I have something related to ask if you don't mind. –  May 18 '14 at 20:29
  • @user3650523 Yes sure! Here you go: http://chat.stackoverflow.com/rooms/53913/discussion-for-user-request – Alexis C. May 18 '14 at 20:33
  • Too bad I have not enough reputation to talk there.. sweat = = –  May 18 '14 at 20:34
  • 1
    Ok, I got all the things I need to solve this question. Thank you very much for your patience and explanation! –  May 18 '14 at 20:55