我已经看到了很多有关HasSets的优秀资源,但是没有什么可以帮助我解决这个特定问题。我正在使用泛型的算法类,并且此分配需要使用扫描程序(已完成)并使用hashSet将txt文件读入系统,加载该txt文件,以便我可以通过用户输入进行读取并找到单词出现的次数。我有返回单词的方法,并且我完成了大多数hashSet和文件阅读器代码。但是我完全停留在如何将整个txt文件存储为一个hashSet上。我无法通过Crime.add使它正常工作,并且尝试了其他几件事。我是否缺少实现此方法的简便方法?谢谢
编辑:作业指导书-程序1(70分)使用Theodore Dostoevsky的小说“ Crime and Punishment”中的单词加载java.util.HashSet(可在黑板上找到该作业的文本文件)。提示用户输入单词并报告该单词是否出现在小说中。
编辑:好的,我已经编写了所有这些代码,并且可以运行,但是找不到在txt文件中肯定存在的单词,因此我在将文件添加到hashSet时出错了。有任何想法吗?我已经尝试过使用数组列表,不同的String实现,但我不知道该从哪里转向。感谢您提供任何有用的信息。
import java.awt.List;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class CandPHashSet {
public static void main(String[] args) throws FileNotFoundException{
Scanner file = new Scanner(new File("crime_and_punishment.txt")).useDelimiter("[ˆa-zA-Z]+");
Scanner input = new Scanner(System.in);
Set<String> crime = new HashSet<String>();
while(file.hasNext()){
String line = file.nextLine();
//String[] words = line.split("[ˆa-zA-Z]+");
for (String word : line.split("[ˆa-zA-Z]+")){
crime.add(line);
}
}
String search;
System.out.println("Enter a word to search for: ");
search = input.next();
if(crime.contains(input)){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
看起来您不需要计算单词出现的次数。您只需要将输入文件字符串拆分成单个单词,然后将它们存储到中即可HashSet<String>
。然后,您应该使用该方法contains()
检查用户输入的单词是否存在于集合中。
您的代码中应该检查几个问题:
您useDelimiter()
在中使用的Scanner
方式不正确。您可能不想指定分隔符,因此将使用默认的空白。
如果您使用空格作为扫描仪定界符,它将已经将您的输入分割为单词。因此,我们不需要逐行读取文件。
您crime.contains(input)
用来查找用户提供的单词。但是input
是一个Scanner
,不是一个String
。您要使用crime.contains(search)
。
修改后的代码如下所示:
// Read the file using whitespace as a delimiter (default)
// so that the input will be split into words
Scanner file = new Scanner(new File("crime_and_punishment.txt"));
Set<String> crime = new HashSet<>();
// For each word in the input
while (file.hasNext()) {
// Convert the word to lower case, trim it and insert into the set
// In this step, you will probably want to remove punctuation marks
crime.add(file.next().trim().toLowerCase());
}
System.out.println("Enter a word to search for: ");
Scanner input = new Scanner(System.in);
// Also convert the input to lowercase
String search = input.next().toLowerCase();
// Check if the set contains the search string
if (crime.contains(search)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句