-2

Determine the number of frequencies of each character in a given paragraph.

this is the output that need to be achieve

this is the input

import java.io.*;
import java.util.*;

public class Solution {

    
    
    static void ASCII(String paragraf)
    {
        int l = paragraf.length();
        int konversi;
        for (int i = 0; i < l; i++) {
            konversi = paragraf.charAt(i);
            System.out.print(konversi);
        }
    }
    
    public static void main(String args[])
    {
        
        Scanner in = new Scanner (System.in);
        String str = in.nextLine();
        
        System.out.println("\t");
        ASCII(str);
    }
 
    
    
}
kiner_shah
  • 3,939
  • 7
  • 23
  • 37

3 Answers3

0

You can use HashMap and store the frequency count for each character.

static void ASCII(String paragraf) {
    int l = paragraf.length();
    Map<Character, Integer> freqMap = new HashMap<>();
    for (int i = 0; i < l; i++) {
        char ch = paragraf.charAt(i);
        freqMap.put(ch, freqMap.getOrDefault(ch,0)+1);
    }
    // freq count
    System.out.println(freqMap.toString());
}
Turtle
  • 667
  • 1
  • 6
  • 18
0

If you want to use Java 8's stream Collectors functionality, try this:

public void ASCII(String paragraph) {

        Map<String, Long> freq = Arrays.asList(paragraph.split("")).stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(freq.toString());
}
0

Try this.

static void ASCII(String paragraph) {
    paragraph.chars()
        .mapToObj(i -> (char)i)
        .collect(Collectors.groupingBy(Function.identity(),
            TreeMap::new, Collectors.counting()))
        .entrySet()
        .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
public static void main(String[] args) {
    String paragraph =
        "Aleph null (also aleph naught or aleph ) is the smallest infinite number. It is the cardinality "
        + "(size) of the set of natural numbers (there are aleph null natural numbers). Georg Cantor "
        + "invented and named the concept. It is the first infinite number in a series of infinite cardinal "
        + "numbers. In fact, it is the size of any set which can be matched with the natural numbers.";
    ASCII(paragraph);
}

output:

 : 66
(: 3
): 3
,: 1
.: 5
A: 1
C: 1
G: 1
I: 3
a: 25
b: 7
c: 8
d: 6
e: 37
f: 9
g: 2
h: 17
i: 25
l: 16
m: 9
n: 30
o: 9
p: 5
r: 18
s: 18
t: 29
u: 12
v: 1
w: 2
y: 2
z: 2