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?
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]);
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With