为什么打印 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 是之前在我的 main 方法中创建的 TextStatistic 对象。然而,当我运行我的程序时,它不是打印出字符出现的频率,而是打印:
a: [I@f84386
b: [I@1194a4e
c: [I@15d56d5
d: [I@efd552
e: [I@19dfbff
f: [I@10b4b2f
而且我不知道我做错了什么。
My program is suppose to count the occurrence of each character in a file ignoring upper and lower case. The method I wrote is:
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;
}
And is printed out using:
for(int letter = 0; letter < 26; letter++) {
System.out.print((char) (letter + 'a'));
System.out.println(": " + ts.getCharTimes(file));
}
Where ts is a TextStatistic
object created earlier in my main method. However when I run my program, instead of printing out the number of how often the character occurs it prints:
a: [I@f84386
b: [I@1194a4e
c: [I@15d56d5
d: [I@efd552
e: [I@19dfbff
f: [I@10b4b2f
And I don't know what I'm doing wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查你的方法的签名;它返回一个整数数组。
ts.getCharTimes(file) 返回 int 数组。因此要打印使用:
您还运行了该方法 26 次,这可能是错误的。由于调用上下文(参数等)不受循环迭代的影响,请考虑更改代码到:
Check out the signature of your method; it is returning an array of ints.
ts.getCharTimes(file) returns int array. So to print use:
You are also running the method 26 times, which is likely to be wrong. Since the call context (parameters and such) is not affected by the iterations of the loop consider changing the code to:
ts.getCharTimes(file) 返回 int 数组。
print ts.getCharTimes(文件)[字母]
ts.getCharTimes(file) returns int array.
print ts.getCharTimes(file)[letter]
这不是垃圾;这是一个功能!
“数组的类具有奇怪的名称,它们不是有效的标识符;”—Java 虚拟机规范。
附录:另请参阅
toString()
。It's not garbage; it's a feature!
"The classes for arrays have strange names that are not valid identifiers;"—The Java Virtual Machine Specification.
Addendum: See also
toString()
.