티스토리 뷰

반응형

⊙ 문제

 

파일 이름을 나타내는 문자열과 특정 문자가 주어지면 파일 속에 포함된 특정 문자의 개수를 찾을 수 있는 CountLetter 클래스를 작성하시오. 다음 코드는 CountLetter 클래스를 테스트하는 프로그램과 실행 결과이다.

 

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("파일 이름을 입력하세요 : ");
        String fileName = in.nextLine();
        System.out.print("세고자 하는 문자를 입력하세요 : ");
        char lookFor = in.nextLine().charAt(0);

        int count = new CountLetter(lookFor, fileName).count();
        System.out.format("%s 파일에 %c 문자가 %d개 %n", fileName, lookFor, count);
    }
}

 

⊙ 문제 접근 과정

 

CountLetter class를 만들어주자


 

⊙ 문제 풀이

 

package chap12;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

class CountLetter {
    char lookFor;
    String fileName;
    int count =0;

    public CountLetter (char lookFor,String fileName) {
        this.lookFor = lookFor;
        this.fileName = fileName;
    }

    public int count() {
        try {
            FileReader reader = new FileReader(fileName);
            BufferedReader br = new BufferedReader(reader);
            char[] buf = new char[10000];
            int bufLen = 0;
            while (true) {
                int c = br.read();
                if (c == -1) break;
                buf[bufLen++] = (char) c;
            }
            for (int i = 0; i < bufLen; i++) {
                if (buf[i] == lookFor) {
                    count++;
                }
            }
            reader.close();
            br.close();
        } catch (IOException e) {
        }
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("파일 이름을 입력하세요 : ");
        String fileName = in.nextLine();
        System.out.print("세고자 하는 문자를 입력하세요 : ");
        char lookFor = in.nextLine().charAt(0);

        int count = new CountLetter(lookFor, fileName).count();
        System.out.format("%s 파일에 %c 문자가 %d개 %n", fileName, lookFor, count);
    }
}

 


⊙ 결과

 


⊙ 마무리

 

 

NONE

 

좋아요는 로그인하지 않아도 누를 수 있습니다!

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함