我的程序应该计算文件中每个字符的出现次数,忽略大小写。我写的方法是:
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 数组。因此要打印使用:
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]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)