2013-03-06 94 views
-1

我正在嘗試編寫一個程序,提示用戶輸入一個字符,並計算所述字符出現在給定文件中的實例的數量。並顯示字符出現的次數。用掃描器計算文件中的特定字符

我真的很茫然,對不起,我沒有太多的代碼,只是不知道從哪裏去。

import java.util.Scanner; 
import java.io.*; 

public class CharCount { 

    public static void main(String[] args) throws IOException { 
     int count = 0; 
     char character; 

     File file = new File("Characters.txt"); 
     Scanner inputFile = new Scanner(file); 

     Scanner keyboard = new Scanner(System.in); 
     System.out.println("Please enter a single character"); 
     character = keyboard.nextLine().charAt(0); 
    } 
} 
+0

哪個_specific part_它是你堅持? – 2013-03-06 06:31:53

+2

http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html?掃描儀不用於緩衝文件io。試圖這樣做會很愚蠢。 – Dmitry 2013-03-06 06:31:59

+0

指定字符並讓程序計算出現字符的次數。 – Champigne 2013-03-06 06:34:11

回答

2

您需要以下代碼才能從文件中讀取數據,並使用您輸入的字符進行檢查。 count將包含指定字符的出現。

try { 
     BufferedReader reader = new BufferedReader(new FileReader(file)); 
     String line = null; 
     while ((line = reader.readLine()) !=null) { 
      for(int i=0; i<line.length();i++){ 
       if(line.charAt(i) == character){ 
        count++; 
       } 
      } 
     } 
    } catch (FileNotFoundException e) { 
     // File not found 
    } catch (IOException e) { 
     // Couldn't read the file 
    } 
+0

另外,還可以使用Commons Lang StringUtils.countMatches - http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/StringUtils.html#countMatches%28java.lang。 CharSequence,%20java.lang.CharSequence%29 – 2013-03-06 06:44:41

+0

@JarleHansen - 很好的選擇:)如果需要,OP可以選擇用'StringUtils.countMatches'來替換那個部分。 – SudoRahul 2013-03-06 06:47:30

+0

謝謝,這工作! – Champigne 2013-03-06 06:54:52