2

First of all,I am newbie in Java and I came across this issue several times. I am trying to return the number of occurrences of a char in a string and I implemented a method called countcharacters which looks like this:

public static int[] countcharacters(String s)
{
    String alphabet="abcdefghijklmnopqrstuvwxyz";

 int[] sircounter=new int[alphabet.length()];
 for(int i=0;i<sircounter.length;i++)
 {
     sircounter[i]=0;
 }

 for(int j=0;j<alphabet.length();j++)
 {
     for(int i=0;i<s.length();i++)
     {
         if(alphabet.charAt(j)==(s.charAt(i)))
         {

             sircounter[j]++;


         }

     }

 }

 return sircounter;
}

In other words, each time a character from alphabet is found in my string ,the argument of the method, the value zero from each position from sircounter is incremented with the number of occurrence. I wanted to print the array position by position but it didn't work and if I do something like this in the main method:

String text="hannah";
System.out.println(Class.countcharacters(text));

I get a hex code: [I@659e0bfd which I don't understand. Could you help me? Many thanks and have a nice day!

  • 2
    I am sure you may find some useful information at: [What's the simplest way to print a Java array?](http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Chris Gao Oct 10 '15 at 10:26
  • 1
    Use the `Arrays.toString()` method. – marstran Oct 10 '15 at 10:26

1 Answers1

1

This is happening because array is treated as an object in java.And when you try to print an object in java you get its hash code(as long as that object hasn't have toString() defined!)

Try this rather-

String text="hannah";
int counter[]=Class.countcharacters(text);
for(int i=0;i<counter.length;i++){
    System.out.print(counter[i]+" ");
}
ValarDohaeris
  • 639
  • 1
  • 6
  • 21