HashMapを使用して文章の単語を統計する
2104 ワード
package johney;
/**
*
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class MyHashMap {
/**
* @param args
*/
static HashMap map;
File file;
static String pathname = "abc.txt";
static FileInputStream fis;
static String word;//
static Set set;
static Iterator iterator;
static char temp;
static int count;
static int i = 0;
static int number = 1;
static boolean state = false;
public static void main(String[] args) {
// TODO Auto-generated method stub
map = new HashMap();
File file = new File(pathname);
try {
fis = new FileInputStream(file);
// System.out.println("The file is exists!");
count = fis.read();
//
while (count != -1) {
//
temp = (char) count;
//
if ((temp >= 'a' && temp <= 'z')
|| (temp >= 'A' && temp <= 'Z')) {
word = word + temp;
state = true;
// System.out.println(word);
}
//
else if (state){
// map
if (word !=" ") {
if (map.containsKey(word)) {
number = map.get(word);
number++;
map.put(word, number);
number = 1;
} else {
map.put(word, number);
}
state = false;
}
word = " ";
}
//
count = fis.read();
count = fis.read();
}
//
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// map
//
set = map.keySet();
iterator = set.iterator();
while (iterator.hasNext()) {
word = (String) iterator.next();
number = map.get(word);
System.out.println(word + ":" + number);
}
}
}