Kat*_*Kat 11 java printing for-loop character
我的程序假设计算文件中每个字符的出现,忽略大写和小写.我写的方法是:
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;
}
Run Code Online (Sandbox Code Playgroud)
并使用以下方式打印出来:
for(int letter = 0; letter < 26; letter++) {
System.out.print((char) (letter + 'a'));
System.out.println(": " + ts.getCharTimes(file));
}
Run Code Online (Sandbox Code Playgroud)
其中ts是TextStatistic我在main方法中先前创建的对象.但是,当我运行我的程序时,它不会打印出字符出现的频率,而是打印:
a: [I@f84386
b: [I@1194a4e
c: [I@15d56d5
d: [I@efd552
e: [I@19dfbff
f: [I@10b4b2f
Run Code Online (Sandbox Code Playgroud)
我不知道我做错了什么.
查看您的方法的签名; 它正在返回一个int数组.
ts.getCharTimes(file)返回int数组.所以要打印使用:
ts.getCharTimes(file)[letter]
Run Code Online (Sandbox Code Playgroud)
您也在运行该方法26次,这可能是错误的.由于调用上下文(参数等)不受循环迭代的影响,请考虑将代码更改为:
int[] letterCount = ts.getCharTimes(file);
for(int letter = 0; letter < 26; letter++) {
System.out.print((char) (letter + 'a'));
System.out.println(": " + letterCount[letter]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1800 次 |
| 最近记录: |