我的程序假设计算文件中每个字符的出现,忽略大写和小写。我写的方法是:
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
我在main方法中创建的对象。但是,当我运行我的程序时,它不会打印出字符出现频率的次数,而是打印:
a: [I@f84386
b: [I@1194a4e
c: [I@15d56d5
d: [I@efd552
e: [I@19dfbff
f: [I@10b4b2f
我不知道我做错了什么。
ts.getCharTimes(file)返回int数组。
print ts.getCharTimes(file)[letter]
ts.getCharTimes(file)返回int数组。
print ts.getCharTimes(file)[letter]
查看您方法的签名;它返回一个int数组。
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]);
}
这不是垃圾;这是一个功能!
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
int:[我@ 58cf40f5
简短:[S @ eb1c260
字节:[B @ 38503429
浮动:[F @ 19908ca1
双倍:[D @ 6100ab23
布尔:[Z @ 72e3b895
char:[C @ 446b7920
“数组的类具有奇怪的名称,这些名称不是有效的标识符;” - Java虚拟机规范。
附录:另见 toString()
。