java - printing unique char and their occurrence -


i new java , programming too. have given assignment count occurrence of unique character. have use array. have 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( +": "+ chararray[i]);             }         }     }  }   

for testchararray output should -

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

but gives me following outpu -

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

how can fix this?

your testchararray array of int. have stored char in it. have cast character int. have make change @ last loop -

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

this casting make int char. each character have int value. example -

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


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -