簡體   English   中英

如何使用掃描儀或緩沖讀取器讀取輸入文件,並計算輸入文件中特定字符的所有出現次數

[英]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

如何使用掃描儀或bufferedreader讀取文件並計算文件中所有字母“ B”?

現在,我正在使用掃描儀讀取文件,每次遇到“ B”時我都有一個int來計數,還有一個int來計數以檢查字符串中的下一個字符,但是它僅適用於第一行,因為當j達到13時,我得到了超出范圍的異常(輸入文件每行包含13個字符,然后換行)。

while (input.hasNext() == true) {
if (input.next().charAt(j) == 'B') {
b++;
}
j++;
}

我曾嘗試在空​​格上拆分,但它告訴我每次都有零個“ 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 ++;
}
}

最終計數將具有'B'的總數

我認為您正在尋找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.");

解決此問題的一種簡單方法是設置掃描儀的定界符:

input.useDelimiter("");

然后,只要下一個標記等於“ B”,就增加您的計數器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM