Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing unique char and their occurrence

Tags:

java

arrays

char

I am new to java and programming too. I have given an assignment to count the occurrence of unique character. I have to use only array. I have do the flowing code -

public class InsertChar{

    public static void main(String[] args){

        int[] charArray = new int[1000];
        char[] testCharArray = {'a', 'b', 'c', 'x', 'a', 'd', 'c', 'x', 'a', 'd', 'a'};

        for(int each : testCharArray){

            if(charArray[each]==0){
                charArray[each]=1;
            }else{
                ++charArray[each];
            }

        }

        for(int i=0; i<1000; i++){
            if(charArray[i]!=0){
                System.out.println( i +": "+ charArray[i]);
            }
        }
    }

}  

For the testCharArray the output should be -

a: 4
b: 1
c: 2
d: 2
x: 2  

But it gives me the following outpu -

97: 4
98: 1
99: 2
100: 2
120: 2  

How can I fix this?

like image 222
k.shamsu Avatar asked Dec 19 '22 03:12

k.shamsu


2 Answers

i is int, so you are printing the integer value of each char. You have to cast it to char in order to see the characters.

change

System.out.println( i +": "+ charArray[i]);

to

System.out.println( (char)i +": "+ charArray[i]);
like image 196
Eran Avatar answered Jan 06 '23 08:01

Eran


You are printing the index as an int. Try casting it to a char before printing it:

for (int i=0; i<1000; i++){
    if (charArray[i]!=0){
        System.out.println( ((char) i) +": "+ charArray[i]);
    }
}
like image 42
Mureinik Avatar answered Jan 06 '23 08:01

Mureinik