Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: homework help
|
Posted: Jan 25, 2003 6:44 PM
|
|
/*
*/
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
public class DisplayWords{
public static void main(String[] args){
DisplayWords displayWords = new DisplayWords();
File textFile = displayWords.getFile();
String fileText = displayWords.readFile(textFile);
Vector wordsInFile = displayWords.getWords(fileText);
ListIterator iterator = wordsInFile.listIterator();
while (iterator.hasNext()){
String nextWord = (String)iterator.next();
System.out.println(nextWord + " " + String.valueOf(displayWords.countOccurrences(fileText, nextWord)));
}
System.exit(0);
}
public File getFile(){
File file = null;
JFileChooser fileChooser = new JFileChooser(new File("."));
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) file = fileChooser.getSelectedFile();
return file;
}
public String readFile(File file){
String text = "";
try{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String nextLine = "";
while ((nextLine = br.readLine()) != null){
text = text + nextLine;
}
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
return text;
}
public Vector getWords(String s){
Vector words = new Vector();
StringTokenizer st = new StringTokenizer(s, " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
while (st.hasMoreTokens()){
String nextWord = st.nextToken();
if ((hasNoPunctuation(nextWord)) && (!isInList(words, nextWord)) && (nextWord.trim().length() > 0)) words.add(nextWord);
}
return words;
}
public boolean hasNoPunctuation(String s){
return !Pattern.matches("\\p{Punct}",s);
}
public boolean isInList(Vector v, String s){
return (v.contains(s.toLowerCase()) || v.contains(s.toUpperCase()));
}
public int countOccurrences(String text, String word){
int count = 0;
StringTokenizer st = new StringTokenizer(text, " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
while (st.hasMoreTokens()){
String nextWord = st.nextToken();
if ((hasNoPunctuation(nextWord)) && (word.toLowerCase().compareTo(nextWord.toLowerCase()) == 0) && (nextWord.trim().length() > 0)) count++;
}
return count;
}
}
|
|