Printing unique char and their appearance

I am new to javaand programming. I gave the task to count the appearance of a unique symbol. I should use only an array. I have the current 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 testCharArrayexit should be -

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

But it gives me the next way out -

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

How can i fix this?

+4
source share
5 answers

Yours testCharArrayis an array from int. You saved char in it. So you need to overlay the character on int. You have to make changes to your last cycle -

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

This cast makes an int char. Each character has an int value. For instance -

'a' has 97, because the value of int 'b' has 98 because it has a intvalue

+1
source

i int, char. , char.

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

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

You print the index as int. Try to execute it before charprinting it:

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

Your program prints asciia character representation. You just need to convert the numbers acsiito characters.

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

}  

That should work.

Further reading:

How to convert ASCII code (0-255) to a string of an associated character?

+2
source

You print ASCII inteveryone’s presentation char. You must convert them to charby casting -

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

All Articles