【问题标题】:Why do I get garbage output when printing an int[]?为什么在打印 int[] 时会得到垃圾输出?
【发布时间】:2010-03-31 23:22:58
【问题描述】:

我的程序假设忽略大小写,计算文件中每个字符的出现次数。我写的方法是:

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

并使用以下方式打印出来:

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

其中 ts 是我之前在 main 方法中创建的 TextStatistic 对象。但是,当我运行我的程序时,它不会打印出字符出现的频率:

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

而且我不知道自己做错了什么。

【问题讨论】:

    标签: java printing for-loop character


    【解决方案1】:

    查看您的方法的签名;它返回一个整数数组。

    ts.getCharTimes(file) 返回 int 数组。所以要打印使用:

    ts.getCharTimes(file)[letter]
    

    您还运行该方法 26 次,这很可能是错误的。 由于调用上下文(参数等)不受循环迭代的影响,请考虑将代码更改为:

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

    【讨论】:

      【解决方案2】:

      ts.getCharTimes(file) 返回 int 数组。

      打印 ts.getCharTimes(file)[字母]

      【讨论】:

      • 谢谢!!像魅力一样工作!
      【解决方案3】:

      这不是垃圾;这是一个功能!

      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 长:[J@b815859 诠释:[I@58cf40f5 短:[S@eb1c260 字节:[B@38503429 浮动:[F@19908ca1 双:[D@6100ab23 布尔值:[Z@72e3b895 字符:[C@446b7920

      “数组的类有奇怪的名称,不是有效的标识符;”—The Java Virtual Machine Specification

      附录:另见toString()

      【讨论】: