문자열과 리스트 다루기

 

-인덱스 메이커

1.입력으로 하나의 텍스트 파일을 읽는다.

2.텍스테 파일에 등장하는 모든 단어들의 목록을 만들고, 각 단어가 텍스트 파일에 등장하는

  횟수를 센다. 단어 개수는 100,000개 이하라고 가정

3.사용자가 요청하면 단어 목록을 하나의 파일로 저장한다.

4.사용자가 단어를 검색하면 테스트파일에 몇번 등장하는지 출력한다.

 

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class code22 {

	static String [] words = new String[100000];
	static int[] count = new int[100000];
	static int n = 0;
	
	public static void main(String[] args) {
		
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("read")) {
				String filename =kb.next();
				makeIndex(filename);
			}
			else if(command.equals("find")) {
				String str = kb.next();
				int index = findWord(str);
				if(index > -1) {
					System.out.println("The word " + words[index] +" appears " + count[index] + " times.");
				}
				else
					System.out.println("The word " + str +" dose not appears ");
			}
			else if(command.equals("saveas")) {
				String filename = kb.next();
				saveAs(filename);
			}
			else if(command.equals("exit")) {
				break;
			}
			
			
		}
		kb.close();
		
		for(int i=0; i<n; i++) {
			System.out.println(words[i]+" "+count[i]);
		}
	}
	static void makeIndex(String filename){
		
		try {
			Scanner inFile = new Scanner(new File(filename));
			while(inFile.hasNext()) {
				String str = inFile.next();
				addWord(str);
			}
			inFile.close();
		} catch (FileNotFoundException e) {
			System.out.print("No File");
			return;
		}
	}
	static void addWord(String str) {
		int index = findWord(str);
		if(index != -1) {
			count[index]++;
		}
		else {
			words[n] = str;
			count[n] =1;
			n++;
		}
	}
	static int findWord(String str) {
		for(int i=0;i<n;i++) 
			if(words[i].equalsIgnoreCase(str)) {
				return i;
			}
		return -1;
	}
	static void saveAs(String fileName) {
		try {
			PrintWriter outFile = new PrintWriter(new FileWriter(fileName));
			for(int i =0;i<n;i++) {
				outFile.println(words[i] + " " + count[i]);
			}
			outFile.close();
		} catch (IOException e) {
			System.out.println("save failed");
			return;
		}
	}
}

output 파일이 생성되었다.

 

모든 기능들을 하나의 함수에서 구현하려하지않고 기능별로 

함수를 만드는 것이 매우중요하다는걸느낌...

+ Recent posts