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

让人想犯罪 __ 提交于 2019-12-10 12:37:32

问题


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.


回答1:


ts.getCharTimes(file) returns int array.

print ts.getCharTimes(file)[letter]




回答2:


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



回答3:


It's not garbage; it's a feature!

public static void main(String[] args) {
    System.out.println(args);
    System.out.println("long:    " + new long[0]);
    System.out.println("int:     " + new int[0]);
    System.out.println("short:   " + new short[0]);
    System.out.println("byte:    " + new byte[0]);
    System.out.println("float:   " + new float[0]);
    System.out.println("double:  " + new double[0]);
    System.out.println("boolean: " + new boolean[0]);
    System.out.println("char:    " + new char[0]);
}
[Ljava.lang.String;@70922804
long:    [J@b815859
int:     [I@58cf40f5
short:   [S@eb1c260
byte:    [B@38503429
float:   [F@19908ca1
double:  [D@6100ab23
boolean: [Z@72e3b895
char:    [C@446b7920

"The classes for arrays have strange names that are not valid identifiers;"—The Java Virtual Machine Specification.

Addendum: See also toString().



来源:https://stackoverflow.com/questions/2557180/why-do-i-get-garbage-output-when-printing-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!