2010-03-31 96 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()