4

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
k.shamsu
  • 69
  • 8

5 Answers5

3

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]);
Eran
  • 387,369
  • 54
  • 702
  • 768
3

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]);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

Your program is printing ascii representation of characters. You just need to convert the acsii numbers to chars.

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( **(char)**i +": "+ charArray[i]);
            }
        }
    }

}  

This should work.

Further reading:

How to convert ASCII code (0-255) to a String of the associated character?

Community
  • 1
  • 1
2

You are printing the ASCII int representation of each char. You have to convert them to char by casting -

System.out.println( (char)i +": "+ charArray[i]);
Mehmood Arbaz
  • 285
  • 1
  • 3
  • 11
1

Your testCharArray is an array of int. You have stored char in it. So you have to cast character to int. You have to make a change at your last for loop -

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

This casting make the int to char. Each character have an int value. For example -

'a' has 97 as it's int value
'b' has 98 as it's int value

Razib
  • 10,965
  • 11
  • 53
  • 80