Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get garbage output when printing an int[]?

My program is suppose to count the occurrence of each character in a file ignoring upper and lower case. The method I wrote is:

public int[] getCharTimes(File textFile) throws FileNotFoundException {

  Scanner inFile = new Scanner(textFile);

  int[] lower = new int[26];
  char current;
  int other = 0;

  while(inFile.hasNext()){
     String line = inFile.nextLine();
     String line2 = line.toLowerCase();
     for (int ch = 0; ch < line2.length(); ch++) {
        current = line2.charAt(ch);
        if(current >= 'a' && current <= 'z')
           lower[current-'a']++;
        else
           other++;
     }
  }

  return lower;
 }

And is printed out using:

for(int letter = 0; letter < 26; letter++) {
             System.out.print((char) (letter + 'a'));
       System.out.println(": " + ts.getCharTimes(file));
            }

Where ts is a TextStatistic object created earlier in my main method. However when I run my program, instead of printing out the number of how often the character occurs it prints:

a: [I@f84386 
b: [I@1194a4e 
c: [I@15d56d5 
d: [I@efd552 
e: [I@19dfbff 
f: [I@10b4b2f 

And I don't know what I'm doing wrong.

like image 355
Kat Avatar asked Mar 31 '10 23:03

Kat


2 Answers

Check out the signature of your method; it is returning an array of ints.

ts.getCharTimes(file) returns int array. So to print use:

ts.getCharTimes(file)[letter]

You are also running the method 26 times, which is likely to be wrong. Since the call context (parameters and such) is not affected by the iterations of the loop consider changing the code to:

int[] letterCount = ts.getCharTimes(file);
for(int letter = 0; letter < 26; letter++) {
  System.out.print((char) (letter + 'a'));
  System.out.println(": " + letterCount[letter]);
}
like image 122
Jacob Krall Avatar answered Sep 21 '22 22:09

Jacob Krall


ts.getCharTimes(file) returns int array.

print ts.getCharTimes(file)[letter]

like image 45
nishu Avatar answered Sep 21 '22 22:09

nishu