简体   繁体   中英

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?

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).

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.

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'

I think the StringUtils .countMatches method is what you're looking for, you can use it like this:

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:

while (input.hasNext()) {
    if (input.next().equals("B"))
        b++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM