인덱스 메이커
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 scan = new Scanner(System.in);
while (true) { // 무한루프
System.out.print("$ ");
String command = scan.next();
if (command.equals("read")) {
String fileName = scan.next();
makeIndex(fileName);
} else if (command.equals("find")) {
String str = scan.next();
int index = findWord(str);
if (index != -1) {
System.out.println("단어 " + words[index] + "는 " + count[index] + "번 언급되었습니다");
} else {
System.out.println("단어 " + str + "는 " + "언급되지 않았습니다");
}
} else if (command.equals("saveas")) {
String fileName = scan.next();
saveAs(fileName);
} else if (command.equals("exit")) {
break;
}
}
scan.close();
for (int i = 0; i < n; i++) {
System.out.println(words[i] + " " + count[i]);
}
}//
static void saveAs(String fileName) {
try {
PrintWriter outFile = new PrintWriter(new FileWriter(fileName));
for (int i = 0; i < n; i++) {
System.out.println(words[i] + " " + count[i]);
}
outFile.close();
} catch (IOException e) {
System.out.println("save failed");
return;
}
}
static void makeIndex(String fileName) {
try {
Scanner inFile = new Scanner(new File(fileName));
while (inFile.hasNext()) { //hasnext가 true인 동안에 while문을 돈다
String str = inFile.next();
addWord(str);
}
inFile.close();
} catch (FileNotFoundException e) {
System.out.println("No file");
return;
}
}
static void addWord(String str) {
int index = findWord(str); // 단어 못 찾으면 return -1
if (index != -1) { // 단어 찾았다면 = words[index] == str일 때
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; // 찾는 단어가 없을 때
}
}//
출력값
$ read sample.txt
$ find mapper
단어 mapper는 2번 언급되었습니다
$ find debug
단어 debug는 언급되지 않았습니다