Reading a text file with a scanner and counting every time each alphabet appears

so I have an array assignment. They are asked to use a scanner to read text files and record the occurrence of each alphabet and save them in a table.

For instance:

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 do not know how to build a method to store occurrences of each alphabet.

It is assumed that it will look like this:

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

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

Hello world

The method ignores any integers or characters and outputs only the char that appeared in the table.

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

I can’t figure it out myself, and any help is much appreciated!

Thanks Shy

+4
source share
2 answers

Map. .

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));
    }
}

Hello World

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

. .

+2

, , a z.

, , 26 ( ).

letter -> index 'a' -> 0, 'b' -> 1 'z' -> 25.

?

, , , ( ) (a - 97, b - 98 ..).

valueOfChar - 'a' , . , , , 0 25, , a z ( ).

, :

  • .
  • ,
  • ( , )
  • ,

, , :

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']);
            }
        }
    }
}

:

d => 1
e => 1
h => 1
l => 3
o => 2
r => 1
w => 1
+1

Source: https://habr.com/ru/post/1541046/


All Articles