复制代码
- //:SortedWordCount.java
- //Countswordsinafile,outputs
- //resultsinsortedform.
- importjava.io.*;
- importjava.util.*;
- importc08.*;//ContainsStrSortVector
- classCounter{
- privateinti=1;
- intread(){returni;}
- voidincrement(){i++;}
- }
- publicclassSortedWordCount{
- privateFileInputStreamfile;
- privateStreamTokenizerst;
- privateHashtablecounts=newHashtable();
- SortedWordCount(Stringfilename)
- throwsFileNotFoundException{
- try{
- file=newFileInputStream(filename);
- st=newStreamTokenizer(file);
- st.ordinaryChar(.);
- st.ordinaryChar(-);
- }catch(FileNotFoundExceptione){
- System.out.println(
- "Couldnotopen"+filename);
- throwe;
- }
- }
- voidcleanup(){
- try{
- file.close();
- }catch(IOExceptione){
- System.out.println(
- "file.close()unsuccessful");
- }
- }
- voidcountWords(){
- try{
- while(st.nextToken()!=
- StreamTokenizer.TT_EOF){
- Strings;
- switch(st.ttype){
- caseStreamTokenizer.TT_EOL:
- s=newString("EOL");
- break;
- caseStreamTokenizer.TT_NUMBER:
- s=Double.toString(st.nval);
- break;
- caseStreamTokenizer.TT_WORD:
- s=st.sval;//AlreadyaString
- break;
- default://singlecharacterinttype
- s=String.valueOf((char)st.ttype);
- }
- if(counts.containsKey(s))
- ((Counter)counts.get(s)).increment();
- else
- counts.put(s,newCounter());
- }
- }catch(IOExceptione){
- System.out.println(
- "st.nextToken()unsuccessful");
- }
- }
- Enumerationvalues(){
- returncounts.elements();
- }
- Enumerationkeys(){returncounts.keys();}
- CountergetCounter(Strings){
- return(Counter)counts.get(s);
- }
- EnumerationsortedKeys(){
- Enumeratione=counts.keys();
- StrSortVectorsv=newStrSortVector();
- while(e.hasMoreElements())
- sv.addElement((String)e.nextElement());
- //Thiscallforcesasort:
- returnsv.elements();
- }
- publicstaticvoidmain(String[]args){
- try{
- SortedWordCountwc=
- newSortedWordCount(args[0]);
- wc.countWords();
- Enumerationkeys=wc.sortedKeys();
- while(keys.hasMoreElements()){
- Stringkey=(String)keys.nextElement();
- System.out.println(key+":"
- +wc.getCounter(key).read());
- }
- wc.cleanup();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- }///:~
欢迎光临 仓酷云 (http://ckuyun.com/) | Powered by Discuz! X3.2 |