Java 搜索对象问题
该程序将查找文本文件中的所有单词,并计算每个单词的查找次数。我们对“单词”的定义将相对粗糙,并且将根据非字母的字符拆分行。我知道有更简单的方法可以做到这一点,但我们需要使用一个类和一个搜索方法,就像我尝试的那样。我不明白为什么它不增加已经在Java 搜索对象问题,java,class,search,if-statement,for-loop,Java,Class,Search,If Statement,For Loop,该程序将查找文本文件中的所有单词,并计算每个单词的查找次数。我们对“单词”的定义将相对粗糙,并且将根据非字母的字符拆分行。我知道有更简单的方法可以做到这一点,但我们需要使用一个类和一个搜索方法,就像我尝试的那样。我不明白为什么它不增加已经在单词列表中的word。我相信如果(foundAt>=0,它可能会完全跳过我的,或者它没有正确地递增它,我倾向于我的搜索方法是错误的,但我无法找出问题所在。非常感谢您提供的任何帮助,谢谢您的时间 public class Hmwk { public stati
单词列表中的word
。我相信如果(foundAt>=0
,它可能会完全跳过我的,或者它没有正确地递增它,我倾向于我的搜索方法是错误的,但我无法找出问题所在。非常感谢您提供的任何帮助,谢谢您的时间
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;
}
}
您的增量函数错误。您已编写:
count =+1;
仅将计数设置为1。要将计数增加1,请输入:
count += 1;
可能与此相关:@BheshGurung,他是我的室友。他用你的方法让他的程序正常运行,并说他感谢你的快速详细的回复,但我正在努力保持我的风格。我只是不知道我在这里哪里出了错。
count += 1;