Java检查文本文件中的每一行字符串并搜索该字符串是否存在

标签 java

你好我正在开发一个程序来检查文本文件中的每一行单词并查看它们是否存在

example of execution

Enter a word to search for: taco

Word 'taco' was found.

Enter a word to search for: asd

Word 'asd' was NOT found.

这是作业的描述

Write a program to read in 100 words from a file. Then, have the user search for a word until they enter 'quit'. The program will read in up to 100 words from a file. The file may or may not contain 100 words but the array should hold up to 100 (if the list does not contain enough words, fill the rest of the array with empty strings). After the file is read in, the program will prompt the user for a search string. The program will then search for the string and tell the user if the word was found or not. The program will continue to get search strings from the user until the user enters 'quit'

到目前为止,这是我的代码,非常不完整

我需要关于我还需要添加/修复什么的建议或建议

谢谢!

import java.io.*;
import java.util.Scanner;
public class project2 {
  public static void main( String[] args ) throws IOException {
    String[] list;
    String  search = "";


    while ( ! search.equals( "quit" ) ) 
    {
        System.out.println( "\nEnter a word to search for: " );  
        Scanner input = new Scanner(System.in);
        search = input.next();
        Scanner file = new Scanner(new File("words.txt"));

   while(file.hasNextLine()){
            String str = file.nextLine();
            if(str.indexOf("search") != -1){
                System.out.println( "Word '" + search + "' was found");}

            else  System.out.println( "Word '" + search + "' was NOT found");}
    }
  } 
}

最佳答案

由于您没有提出具体问题,但似乎是在寻求建议,因此我会指出我看到的一些缺陷以及改进。

潜在缺陷:

  1. 您正在检查文件的每一行而不是整个文件。我对您的要求的解释是您需要确定所提供的词是否存在于文件,而不是包含它的行。
  2. 您拆分文件的唯一边界是新行(通过使用 readLine())。但是,我想知道为什么要求使用“单词”这个词。你应该在单词边界上拆分吗?例如,如果文件包含“我将到达华盛顿州塔科马”这句话,它将匹配“Taco”的搜索,这与塔科马市无关。
  3. 每次输入一个单词时,您都在重新扫描整个文件。您的要求没有说明您是否需要担心文件在运行时发生变化。我猜不会,这意味着您可能只需阅读一次并将其解析为适当的数据结构即可。
  4. 您正在对文件进行线性扫描。找到所有单词,将它们存储到为快速搜索优化的数据结构中会更快。
  5. 小写与大写匹配的要求/预期行为是什么?“taco”应该匹配“Taco”吗?

我的建议:

  1. 在进入输入循环之前,逐行读取文件内容,并按空格拆分以查找“单词”。
  2. 将每个词存储到针对次线性搜索优化的数据结构中。我将把它作为练习留给您寻找合适的练习。检查 Java 集合框架。
  3. 如果您想以不区分大小写的方式处理此问题,请在将每个单词添加到您的集合之前将其小写。
  4. 在您的输入循环中,对先前构建的单词集合执行 Collection.contains(o) 搜索,以查看它是否出现在文件中。
  5. 如果您想以不区分大小写的方式处理此问题,请在调用 Connection.contains(o) 之前将搜索词小写。

关于Java检查文本文件中的每一行字符串并搜索该字符串是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306298/

相关文章:

java - 具有限制行数的结果集 jdbc 驱动程序

java - 如何使 RealmList 可打包

Java Android Basic 游戏 - 使用共享首选项保存高分 - 初学者

java - 在应用程序启动时设置环境变量

java - 在 Executor.execute() 中设置超时

java - Android autoCompleteTextView 找不到第一个适配器字符串的第一部分

java - 从java代码重新启动apache服务器?

java - 获取 Java 一年中的所有双周日期

java - 表达式的类型必须是数组类型,但它解析为 SoapObject

java - LG 设备上的 Android 6.0 (Marshmallow) 中的 new String(byte[]) 损坏?