I'm attempting to make an array of WordCount
s, then iterate through a file line by line separating it into tokens using a split method. Then for each token, if it's in wordList
, increment count
, and if it's not in wordList
just simply add it to the list.
Hmwk
class -
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
int n=0;
WordCount[] wordList= new WordCount[10000];
Scanner words = new Scanner(new File("input.txt"));
while (words.hasNextLine() && n < 10000) {
String line = words.nextLine();
String[] tokens = line.split("[^\\p{Alpha}]");
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].length() > 0) {
WordCount word = new WordCount(tokens[i]);
int foundAt = search(wordList, word, n);
if (foundAt >= 0) {
word.increment();
} else {
wordList[n]=word;
n++;
}
}
}
}
//Arrays.sort(wordList);
String alphabeticFileName = "alphabetic.txt";
String frequencyFilename = "frequency.txt";
PrintWriter output = new PrintWriter(alphabeticFileName);
for (int i=0; i < n;i++) {
output.println(wordList[i].toString());
}
output.close();
//Sort on frequency somehow
PrintWriter output2 = new PrintWriter(frequencyFilename);
for (int i=0; i < n; i++) {
output2.println(wordList[i].toString());
}
output2.close();
}
public static int search(WordCount[] list,WordCount word, int n) {
int result = -1;
int i=0;
while (result < 0 && i < n) {
if (word == list[i]) {
result = i;
}
i++;
}
return result;
}
}
WordCount
class -
class WordCount {
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord) {
setWord(aWord);
count = 1;
}
private void setWord(String theWord) {
word = theWord;
}
public void increment() {
count += 1;
}
public static void sortByWord() {
compareByWord = true;
}
public static void sortByCount() {
compareByWord = false;
}
public String toString() {
String result = String.format("%s (%d)", word, count);
return result;
}
}
It compiles and runs fine, but for some reason I'm given
Peter (1) Piper (1) picked (1) a (1) peck (1) of (1) pickled (1) peppers (1) A (1) peck (1) of (1) pickled (1) peppers (1) Peter (1) Piper (1) picked (1) If (1) Peter (1) Piper (1) picked (1) a (1) peck (1) of (1) pickled (1) peppers (1) Where (1) s (1) the (1) peck (1) of (1) pickled (1) peppers (1) that (1) Peter (1) Piper (1) picked (1)
as output. Is there something wrong with my class, or my search method here? I'm lost, any and all help is much appreciated.