[英]How do I read in an input file with a scanner or buffered reader and count all the occurences of a specific character in the input file
How can I read in a file with a scanner or bufferedreader and count all of the letter "B" in the file? 如何使用扫描仪或bufferedreader读取文件并计算文件中所有字母“ B”?
Right now I am taking in the file with a scanner and I have an int to count up every time I run into a "B", as well as an int to count up in order to check the next character in the string, but it only works for the first line because, when j reaches 13 I get an out of bounds exception(the input file has 13 characters on each line, then a line break). 现在,我正在使用扫描仪读取文件,每次遇到“ B”时我都有一个int来计数,还有一个int来计数以检查字符串中的下一个字符,但是它仅适用于第一行,因为当j达到13时,我得到了超出范围的异常(输入文件每行包含13个字符,然后换行)。
while (input.hasNext() == true) {
if (input.next().charAt(j) == 'B') {
b++;
}
j++;
}
I've tried splitting on whitespace, but it tells me there are zero "B"s every time, which isn't true. 我曾尝试在空格上拆分,但它告诉我每次都有零个“ B”,这是不正确的。
static int count;
while(input.hasNext())
{
String line=input.next();
getCount(line);
}
private static int getCount(String line)
{
char[] arr=line.toCharArray();
for(int i=0;i<arr.length;i++)
{
if(arr[i]=='B')
count ++;
}
}
finally count will .have total number of 'B' 最终计数将具有'B'的总数
I think the StringUtils .countMatches method is what you're looking for, you can use it like this: 我认为您正在寻找StringUtils .countMatches方法 ,可以像这样使用它:
int occurences=0;
while(input.hasNext())
{
String line=input.next();
occurences+=StringUtils.countMatches(line, "B");
}
System.out.println("There are "+occurences+" occurences of the character B in the file.");
A simpler way to solve this solution is to set the delimiter of your Scanner: 解决此问题的一种简单方法是设置扫描仪的定界符:
input.useDelimiter("");
Then, whenever the next token is equal to "B", increment your counter: 然后,只要下一个标记等于“ B”,就增加您的计数器:
while (input.hasNext()) {
if (input.next().equals("B"))
b++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.