首页 > 解决方案 > txt文件的Java顺序搜索

问题描述

该程序在文件中搜索给定条目。我认为我的主要打印声明是不正确的。当我运行命令提示符时,我的程序打印出“未找到物品猫!” 即使“cat”出现在程序检查的列表中。清单如下: CAT RAT VAT MAT BAT HAT ZAT PAT SAT TAT

这是我的程序:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class SequentialSearchFile {
    public static void main(String args[])
    {
        // String to contain filename
        String fileName = "";
        // String to contain search item;
        String searchItem;
        Scanner s = new Scanner (System.in);
        
            // If there is one command-line parameter
            if (args.length == 1 )
            {
                fileName = args[0]; // assume that it is the filename
                System.out.print("Please enter search item: ");
                searchItem = s.nextLine();
            }
            // If there are two command-line parameters
            else if (args.length == 2)
            {
                fileName = args[0]; // take them as the filename
                searchItem = args[1]; // and as the search item
            }
            else {
                System.out.print("Please enter file name: ");// no command line parameters?
                fileName = s.nextLine();                     // prompt user for both
                System.out.print("Please enter search item: "); 
                searchItem = s.nextLine();
            }
            searchItem = searchItem.trim(); // trim any extra spaces from search item
            
            System.out.println("Searching file" + fileName + "...");
            System.out.println("Item " + searchItem + " was " +
                                (sequentialSearch(fileName, searchItem) ?"" : "NOT ") + "found!");
    }
    
    // method opens file and searches the contents
    public static boolean sequentialSearch (String fileName, String searchItem) {           
        boolean result = false;                               // default response is not found
        try {
            Scanner f = new Scanner(new File(fileName));      // get a connection to the file
            String fileItem;
            while(f.hasNext())
                {
                    fileItem = f.nextLine();                  // check each entry against the search item
                    if(searchItem.equalsIgnoreCase(fileName)) 
                    {
                        result = true;                       // if found, set result to true
                        break;                               // and break out of the while loop
                    }
                }
            }
        catch(FileNotFoundException e) {                    // if the file wasn't there,
            System.out.println(e.toString());               // show the exception text
            System.exit(0);                                 // and exit
        }
        return result;                                      // return the result
    }
}

标签: javasearchsequential

解决方案


实施有几个问题。

首先,您使用 (这是正确的!)检查下一个字符串,hasNext()然后使用 读取整行nextLine()而不是使用next().

其次,在您比较searchItem的每次迭代中,fileName而不是fileItem您从文件中读取的:

Scanner f = new Scanner(new File(fileName));
String fileItem;
while(f.hasNext()) {
    fileItem = f.next(); // A single item is read with next(), not nextLine()
    if(searchItem.equalsIgnoreCase(fileItme)) { // searchItem is compare to fileItem
        result = true;
        break; 
    }
}

注意:
为简洁起见,答案中省略了错误处理和资源管理,但当然应该出现在您的实际代码中。


推荐阅读