2012-03-29 2 views
0

나는 모든 수를 1 카운터에 집계하는 방법을 알아 내려고 노력하고 있는데, 이것은 각 라인에서 'a'의 수를 세고 모든 라인을 하나의 라인에 집계하는 방법을 알고 싶습니다.JavaIntro.txt 파일에 "a"문자가 나타나는 횟수를 세는 프로그램을 작성하십시오.

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


public class CountTheNumberOfAs { 
    public static void main(String[] args)throws IOException 
    { 

     String fileName = "JavaIntro.txt"; 
     String line = ""; 
     Scanner scanner = new Scanner(new FileReader(fileName)); 
     try { 

      while (scanner.hasNextLine()){ 
      line = scanner.nextLine(); 
      int counter = 0; 

      for(int i=0; i<line.length(); i++) { 
       if(line.charAt(i) == 'a') { 
        counter++; 

       } 


      } 

      System.out.println(counter); 
      } 
     } 
     finally { 

      scanner.close(); 


    }}} 
+0

디버거는 이와 같은 오류를 찾는 데 큰 도움이됩니다. –

답변

2

while 루프 외부에서 카운터를 이동해야합니다. (인쇄용과 동일) :

int counter = 0; 
while (scanner.hasNextLine()){ 
// ... 
} 
System.out.println(counter); 
+0

나는 그것이 단지 1 2 3 3을 개별 라인에 포함 시키려고 노력했다. 나는 무엇을 놓치고 있는가? –

+0

이전 위치에서 해당 행을 제거 했습니까? – MByD

+0

예. 원본을 제거하고 while 루프 외부에 배치했습니다. –

관련 문제