2013-11-23 51 views
-1

我想要打印出有多少字母「a」。 它不斷給我0 ...任何幫助?計算字符串中出現的字符

JFileChooser chooser = new JFileChooser(); 
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
    File myfile = chooser.getSelectedFile(); 
    try { 

     Scanner in = new Scanner(myfile); 
     String word = in.nextLine(); 
     int counter = 0; 
     for (int i = 0; i < word.length(); i++) { 
      if (word.charAt(i) == 'a') { 
       counter++; 
      } 
     } 

     System.out.println("# of chars: " + counter); 
    } catch (IOException e) { 
     System.err.println("A reading error occured"); 
    } 
} 
+2

打印'word',你會得到什麼? – arshajii

+0

您是否嘗試在循環之前打印「單詞」? –

+1

您只檢查第一行。文件中的第一行是否有'a'? – Adarsh

回答

0
JFileChooser chooser = new JFileChooser(); 
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
File myfile = chooser.getSelectedFile(); 
try { 

    Scanner in = new Scanner(myfile); 

    int counter = 0; 
while(in.hasNextLine()){ 
String word = in.nextLine(); 
    for (int i = 0; i < word.length(); i++) { 
     if (word.charAt(i) == 'a') { 
      counter++; 
     } 
    } 
} 

    System.out.println("# of chars: " + counter); 
} catch (IOException e) { 
    System.err.println("A reading error occured"); 
} 
} 
+0

感謝您的幫助! – user2856344

+0

@ user2856344是否有效? – Adarsh

+0

我該如何計算字母a和字母b? – user2856344

1

除了讀取文件的任何問題,也嘗試使用StringUtils countMatches。它已經在普通的語言中,而且用它來代替。

例如

int count = StringUtils.countMatches(word, "a"); 
2

更簡單(一行)計數字符出現的方式是:

int count = word.replaceAll("[^a]", "").length(); 

這將替換每一個字符是一個 「A」 用空白不是 - 有效刪除它 - 給你一個只包含原始字符串的「a」字符的字符串,然後你得到這個長度。

+0

美麗;可能不是儘可能的資源利用率,但是寫得很快。 – tucuxi