2010-03-31 92 views
11

我的程序是假设计算忽略大写和小写的文件中每个字符的出现次数。我写的方法是:打印int []时为什么会出现垃圾输出?

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是在我的主要方法之前创建一个TextStatistic对象。然而,当我运行我的程序,而不是打印出来的字出现的频率是多少打印:

a: [[email protected] 
b: [[email protected] 
c: [[email protected] 
d: [[email protected] 
e: [[email protected] 
f: [[email protected] 

而且我不知道我做错了。

回答

3

ts.getCharTimes(文件)返回int数组。

打印ts.getCharTimes(文件)[信]

+0

谢谢!像魅力一样工作! – Kat 2010-03-31 23:28:00

+0

和什么smink回答 – Nishu 2010-04-01 00:26:36

9

查看你方法的签名;它返回一个int数组。 (文件)返回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

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

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: [[email protected] 
int:  [[email protected] 
short: [[email protected] 
byte: [[email protected] 
float: [[email protected] 
double: [[email protected] 
boolean: [[email protected] 
char: [[email protected] 

“数组的类有奇怪的名字不是有效的标识;” - The Java Virtual Machine Specification

附录:另请参阅toString()