【发布时间】:2013-09-17 07:13:51
【问题描述】:
我想计算输入网址中的所有字母。我不想区分大写或小写字母。 a的总数将存储为total[0]中的整数,b的总数为total[1]等。
知道如何使用 InputStream 实现这一点吗?
public static int[] letterFrequency(String url) throws IOException {
InputStream inn= new BufferedInputStream((new URL(url)).openStream());
char[] c= {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'æ', 'ø', 'å'};
int[] total= new int[29];
for(int i= 0; i< c.length; i++) {
int counter= 0;
while(inn.available()!= 0) {
if(inn.read()== c[i])
counter++;
}
total[i]= counter;
}
return total;
}
编辑:
感谢所有回答者!你很棒!! ;)
【问题讨论】:
-
首先你为什么要从 InputStream 中准备好字符?不是已经有 inputstreamReader 类了吗?
-
您可以使用
Map并将每个计数器存储在其中,并将字母的小写/大写作为键。 -
使用
Map和toLowerCase方法忽略大小写。你的方法行不通……
标签: java char inputstream counting bufferedinputstream