【问题标题】:Searching through Objects Issue搜索对象问题
【发布时间】:2014-04-15 21:56:21
【问题描述】:

该程序是查找文本文件中的所有单词并计算每个单词被找到的次数。我们对“单词”的定义相对粗略,将通过根据非字母字符拆分行来完成。我知道有更简单的方法可以解决这个问题,但我们需要使用一个类和一个搜索方法,就像我尝试的那样。我不明白为什么它不增加已经在wordList 中的word。我相信它要么完全跳过了我的if (foundAt >=0,要么没有正确增加它,我倾向于我的search 方法是错误的,但我无法找出问题所在。非常感谢您的任何帮助,感谢您的宝贵时间。

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)

【问题讨论】:

  • @BheshGurung 那是我的室友。他使用您的方法使他的程序正常工作,并说他感谢快速详细的响应,但我正在努力保持我的风格。我只是不知道我哪里出错了。

标签: java class search if-statement for-loop


【解决方案1】:

你的增量函数是错误的。你写过:

count =+1;

仅将计数设置为一。要将 count 加一:

count += 1;

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多