2013-11-23 1 views
-1

나는 "a"라는 문자가 몇개인지를 인쇄하려고합니다. 계속해서 도움을 청합니다. 파일을 읽는 모든 문제를 넘어문자열에서 카운트 문자가 발생했습니다.

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

인쇄 '단어', 당신은 무엇을 얻습니까? – arshajii

+0

루프 앞에'word'를 출력하려고 했습니까? –

+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를 사용해보십시오. 이미 일반적인 랭 (lang)에 있지만, 그 대신에 그것을 사용하십시오. 예를

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

더 간단한 (한 줄)는 문자의 발생을 계산의 방법을

입니다 : 이것은 "A"빈과 함께 아니다 모든 문자 대체

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

- 효과적으로 삭제 - 원래 문자열의 "a"문자 만 포함 된 문자열을 남겨 둡니다. 그런 다음 길이를 얻습니다.

+0

아름답다. 가능한 자원 효율적인 것은 아니지만 신속하게 작성할 수 있습니다. – tucuxi

관련 문제