我在让我的程序正常运行时遇到了一些麻烦。差不多完成了,除了这部分我已经工作了一个星期,但无法完成。程序应该计算每个单词出现的次数。
输入:
This is my file, yes my file My file.. ? ! , : ; / \ |" ^ * + = _( ) { } [ ] < >
输出应如下所示:
file *3
is *1
my *3
this *1
yes *1
这是我的代码
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
public class cleanup3 {
public cleanup3() {}
public static void main(String[] args) {
try{
ArrayList myArraylist = new ArrayList();
System.out.println("Please Enter file");
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream) ;
String fileName = bufRead.readLine();
BufferedReader file = new BufferedReader(new FileReader(fileName));
String s = null;
while((s = file.readLine()) != null) {
String updated2 = s.replaceAll("[\\.\\,\\?\\!\\:\\;\\/\\|\\\\\\^\\*\\+\\=\\_\\(\\)\\{\\}\\[\\]\\<\\>\"]+"," ");
//note to self: missing Single quotes (only if the LAST character of a token)
StringTokenizer st = new StringTokenizer(updated2.toLowerCase());
while (st.hasMoreTokens()) {
String nextToken = st.nextToken();
String myKeyValue = (String)myMap.get(nextToken);
if(myKeyValue == null){
myMap.put(nextToken, "1");
}
else{
int mycount = Integer.parseInt(myKeyValue) + 1;
myMap.put(nextToken, String.valueOf(mycount));
}
System.out.println(nextToken);
}
}
System.out.println( updated2.toLowerCase());
myArraylist.add(updated2.toLowerCase());
}
Collections.sort(myArraylist);
String outPutFileName = fileName + "sorted.txt";
PrintStream ps = new PrintStream( outPutFileName );
ps.print(myArraylist.toString());
ps.flush();
ps.close();
}
catch (Exception e){
System.out.println(e.toString());
}
}