代码:
package test1;
import java.io.FileReader;
import java.io.IOException;
class Word{
String value;
int count;
Word next;
public Word(String s,int count) {
this.value = s;
this.count = count;
next = null;
}
public Word() {
this.value = "";
this.count = 0;
next = null;
}
}
public class CountWord {
private static FileReader f;
public static void main(String[] args) throws IOException {
Word wd = new Word();
Word list,newWord;
String st = "";
char[] ch = new char[1];
boolean exist = false;
f = new FileReader("C:/Users/admin/Desktop/File/n2.txt");
while(f.read(ch)!=-1) {
if(String.valueOf(ch).equals("\"")||String.valueOf(ch).equals(" ")||String.valueOf(ch).equals("\r")||String.valueOf(ch).equals("\n")||String.valueOf(ch).equals(".")||String.valueOf(ch).equals(",")||String.valueOf(ch).equals("'")) {
list = wd;
while(list!=null) {
if(list.value.equalsIgnoreCase(st)) {
list.count++;
exist = true;
break;
}else {
list = list.next;
}
}
if(exist==false) {
newWord = new Word(st,1);
newWord.next = wd.next;
wd.next = newWord;
}else {
exist = false;
}
st = "";
}else {
st+=String.valueOf(ch);
}
}
System.out.println("前5个出现频率最高的单词为:");
for(int i=1;i<=5;i++) {
Word w = new Word("",0);
for(list =wd.next;list!=null;list=list.next) {
if(list.count>w.count) {
w = list;
}
}
System.out.println("第"+i+"个"+w.value+"个数为"+w.count);
for(list =wd;list.next!=w;list=list.next);
list.next=list.next.next;
}
f.close();
}
}
图片: