Meryel Meryel - 2 years ago 98
Java Question

Output one occurence of a character in a string c#

This program should output only one occurrence of a character in a string then specify the number of occurrence in that string. It should be sorted in ascending order depending on the number of occurrences of that particular character. It's working except on the

part. Does it have something to do with ASCII codes or something?

Desired Output:

b: 1




Code's output:

ü: 1

ý: 1

þ: 2

ÿ: 2

public class HuffmanCode {
static String string;
static Scanner input = new Scanner(;

public static void main(String args[]){
System.out.print("Enter a string: ");
string = input.nextLine();

int count[] = countOccurence(string);

for (int i = 0; i < count.length; i++) {
if (count[i] > 0)
System.out.println((char)i + ": " + count[i]);

public static int[] countOccurence(String str){
int counts[] = new int[256];

for(int i=0;i<str.length();i++){
char charAt = str.charAt(i);

return counts;

Answer Source

Create a list and sort it instead of sorting count.

    List<int[]> list = new ArrayList<>();
    for (int i = 0; i < count.length; i++) {
        if (count[i] > 0)
            list.add(new int[] {i , count[i]});
    Collections.sort(list, Comparator.comparing(a -> a[1]));
    for (int[] a : list) {
        System.out.println((char)a[0] + ": " + a[1]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download