该程序将查找文本文件中的所有单词并计算每个单词的找到次数。我们对'"字"的定义将是相对粗糙的,将通过基于不是字母的字符分割线来完成。我知道有更简单的方法可以解决这个问题,但我们需要使用类和我尝试过的搜索方法。我无法弄清楚为什么它没有增加word
中已经存在的wordList
。我相信它要么完全跳过if (foundAt >=0
,要么没有正确递增,我倾向于我的search
方法错了,但我可以&# 39;找出问题所在。感谢你的时间,非常感谢任何和所有的帮助。
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)
{
wordList[foundAt].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.equals(list[i]))
{
result = i;
}
i++;
}
return result;
}
}
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;
}
}
输出:
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)
答案 0 :(得分:1)
您的增量功能错误。你写过:
count =+1;
仅将计数设为1。要将计数增加1,请输入:
count += 1;