Meryel Meryel - 7 months ago 12
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

(char)i
part. Does it have something to do with ASCII codes or something?



Desired Output:

b: 1

d:1

a:2

s:2




Code's output:

ü: 1

ý: 1

þ: 2

ÿ: 2


public class HuffmanCode {
static String string;
static Scanner input = new Scanner(System.in);

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

int count[] = countOccurence(string);
Arrays.sort(count);

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);
counts[(int)charAt]++;
}

return counts;
}
}

Answer

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