如果有人可以帮我弄清楚如何搜索文件中是否存在某个单词,我将非常感激。我知道如何阅读整个文本文件。
这就是我到目前为止所做的:
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word you would like to search for:");
String word = sc.nextLine();
List<String> words = new ArrayList<>();
try {
sc = new Scanner(file).useDelimiter( ",");
while (sc.hasNext()) {
final String wordFromFile = sc.nextLine();
if (wordFromFile.contains(word)) {
// a match!
System.out.println("The entered word: " + word + " exists in the dictionary");
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
}
答案 0 :(得分:1)
只需遍历文件中的所有单词,首先将每个单词插入到文件HashSet
中。这是要完成的线性时间O(n)
,因为你必须在整个文件中读取它。
假设文件中有一个单词,它就像:
HashSet<String> set = new HashSet<>();
while (sc.hasNext()) {
set.add(sc.nextLine();
}
如果有人贴纸,他们真的希望它读取到列表类型集合,您可以从列表中生成这样的HashSet:
Set<String> set = new HashSet<>(wordList);
注意:此转换操作也是O(n)
,因此要将其读入列表并转换为O(2n)
,仍为O(n)
,但如果这个列表远非最佳
为了查找和/或插入您检查的新单词,可以在O(1)
时间内完成。
if (set.contains(word)) {
//...blah..blah...bla...
} else {
set.add(word);
}
因此名称HashSet
中的哈希。
答案 1 :(得分:0)
这可能有助于您理解
public static void main(String a[]){
File file = new File("words.txt");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word you would like to search for:");
String word = sc.nextLine();
boolean exist = false;
List<String> words = new ArrayList<String>();
sc = new Scanner(file);
while(sc.hasNext()){
words.add(sc.next());
}
for(int i=0;i<words.size();i++){
if(words.get(i).equals(word)){
System.out.println("The entered word: " + word + " exists in the dictionary");
exist = true;
break;
}
}
if(!exist){
System.out.println("This word is not in the dictionary.");
System.out.println("Do you want to add it");
if(System.in.read() == 'y'){
words.add(word);
}
}
}
答案 2 :(得分:0)
如果您使用的是分隔符,则不应使用nextLine()
。另外,如果您要将元素添加到List
使用.add(Object)
public static void main(String[] args) throws IOException {
File file = new File("C:/Users/pelos.W2017/workspace/Frac/src/words.txt");
Scanner sc = null;
List<String> words = new ArrayList<>();
try {
sc = new Scanner(file);
sc.useDelimiter(",");
while (sc.hasNext())
words.add(sc.next());
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
return;
}
sc = new Scanner(System.in);
boolean wordExists = false;
String word = null;
System.out.println("Enter a word you would like to search for:");
word = sc.next();
if (!words.contains(word)) {
System.out.println("The entered word: " + word + " doesn't exist in the dictionary");
System.out.println("Add to list?");
if(sc.next().equals("yes")){
words.add(word);
}
}
else{
wordExists = true;
}
System.out.println("The entered word: " + word + " exists in the dictionary");
}