📄 wordcount.java
字号:
package eclipse.workspace.Word.src;
import eclipse.workspace.Word.src.WordCount;
import java.io.FileNotFoundException;
import java.util.*;
public class WordCount {//implements java.lang.Comparable<Object>
FileWordReader fwr;
Map<String,Integer> wordList;
int topNum; //the most popular words number,i,e top "10"
int sum=0; //count the topNum words appeared time
Object[] obj; //to set the sorted wordlist
private int[] value;
private String[] key;
public WordCount(String name)
{
try {
fwr=new FileWordReader(name);
wordList=new HashMap<String,Integer>();
this.setTopNum(10);
this.setWordMap();
this.sortTopWordValue();
this.setLists();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void setTopNum(int a)
{
topNum=a;
}
public void setWordMap() //put different words in the map and count their appeared time
{
int count;
String key=fwr.getNextWord();
while(key!=null)
{
count=1;
key=key.toLowerCase();
if(wordList.containsKey(key))
{
count=wordList.get(key);
count++;
wordList.put(key, count);
}
else
{
wordList.put(key, count);
}
key=fwr.getNextWord();
}
}
public int getWordMapLength()
{
return wordList.size();
}
public int[] getValueList()
{
return value;
}
public void setLists()
{
key=new String[wordList.size()];
value=new int[wordList.size()];
for(int i=0;i<wordList.size();i++)
{
Map.Entry<String, Integer> entry=(Map.Entry<String, Integer>)obj[i];
value[i]=entry.getValue();
key[i]=entry.getKey();
}
}
public String[] getWordList()
{
return key;
}
public void sortTopWordValue()//sort and print the most popular words in the file
{
List myList=new ArrayList(wordList.entrySet());
Collections.sort(myList, new Comparator(){
public int compare(Object o1,Object o2){
Map.Entry< String, Integer> obj1=(Map.Entry<String, Integer>)o1;
Map.Entry<String, Integer> obj2=(Map.Entry<String, Integer>)o2;
return obj2.getValue().compareTo(obj1.getValue());
}
}
);
obj=myList.toArray();
for(int i=1;i<=topNum;i++)
{
Map.Entry<String, Integer> entry=(Map.Entry<String, Integer>)obj[i-1];
System.out.println("Top"+i+":\t"+entry.getKey()+" \tAppeared Time:"+entry.getValue());
sum+=entry.getValue();
}
/*for(String k:wordList.keySet())
{
System.out.println("×Key:"+k+" Value:"+wordList.get(k));
}*/
}
public Object[] getSortedList()
{
if(obj==null)
this.sortTopWordValue();
return obj;
}
public void grapPWord(long num,Object[] obj)
{
System.out.println("The graphic show of the top "+topNum+" Words(Percentage)");
for(int i=0;i<this.wordList.size();i++)
{
Map.Entry<String, Integer> entry=(Map.Entry<String, Integer>)obj[i];
System.out.printf("%20s",entry.getKey()+"\t");
for(int j=0;j<=entry.getValue()*1000/num;j++)
System.out.print('_');
System.out.printf("%.2f", (float)entry.getValue()*100/num);
System.out.println("%");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -