从文件中搜索字符串,并在java中返回该字符串?

时间:2014-05-20 20:53:53

标签: java string file

我仍然是Java的新手,但我一直试图让我的程序让用户输入一个名称并在文件中搜索该名称,如果该名称在文件中,它将返回到主要。如果该名称不在文件中,程序将要求用户输入另一个名称,直到他们输入文件中的名称。如果用户输入“退出”,程序将退出。我的代码没有做我正在寻找的东西,但我希望它能得到我的观点..

public static String getName(File inFile, Scanner console) throws FileNotFoundException {       //Retrieves name from the user and returns it to main
    System.out.print("Enter a name (or quit): ");   
    String name = console.next();
    System.out.println();


    Scanner scanner = new Scanner(inFile);
    while (scanner.hasNextLine()) {
       String lineFromFile = scanner.nextLine();
       if(lineFromFile.contains(name)) { 
           // a match!
           System.out.println("I found " +name);
       }   

       if(name.equalsIgnoreCase("quit")){
           System.exit(0);
       }
       else{
           console.nextLine(); 
             System.out.println("That name wasn't found.");
             System.out.println("Enter a name (or quit): ");
       }

    }

    return name;
}

3 个答案:

答案 0 :(得分:0)

在下面的代码中,我们有一个外部循环while(!hasName),它导致程序不断询问一个名称,直到它在你的文件中找到一个名字。

您可以进行一些改进,以便只阅读一次文件,但这似乎超出了本问题的范围。

试试这个:

    public static String getName(File inFile, Scanner console) throws FileNotFoundException {       //Retrieves name from the user and returns it to main
    boolean hasName = false;
while(!hasName)
{
    System.out.print("Enter a name (or quit): ");   
    String name = console.next();
    System.out.println();


    Scanner scanner = new Scanner(inFile);
    while (scanner.hasNextLine()) {
       String lineFromFile = scanner.nextLine();
       if(lineFromFile.contains(name)) { 
           // a match!
           System.out.println("I found " +name);
           hasName=true;
           break;
       }   

       if(name.equalsIgnoreCase("quit")){
           System.exit(0);
       }

    }
}
    return name;
}

答案 1 :(得分:0)

好吧,你的循环非常糟糕,首先,你不想检查用户是否用文件的每一行写了quit(你现在做的是什么)。在开始之前检查是否在循环中读取文件。

其次,你不知道你的文件不包含name,直到你阅读并检查它的所有行,只是因为你的话不是第一次这条线并不意味着它不在第二或第三。您需要在之后打印name not found ,并且仍然没有找到它。

答案 2 :(得分:0)

我知道这已经得到了一些答案,但我想你可能会喜欢一个有评论的人来解释一下会发生什么。我还用更常见的Java风格重新格式化了它。

public static void main(String[] args) throws FileNotFoundException {
    String name = getName(new File("names.txt"), new Scanner(System.in));
}

//Retrieves name from the user and returns it to main
public static String getName(File inFile, Scanner console) throws FileNotFoundException {
    //Define these outside the loop because is slightly more efficient
    String lineFromFile;
    String name;
    Scanner scanner;

    // Infinite loop, this is okay because we can break out of it later
    while (true) {
        System.out.print("Enter a name (or quit): ");   
        name = console.nextLine().trim();
        if(name.equalsIgnoreCase("quit")) {
            /* It is generally bad form to use System.exit.
             * Just return control to main and let it finish cleanly.
            */
            return null;
        }

        /* We have to keep reopening the file for each go as scanner does not have a rewind option
         * You could use a different reader instead to solve this.
        */
        scanner = new Scanner(inFile);
        while (scanner.hasNextLine()) {
            /* Get the next line and trim any trailing spaces
             * This could give a NullPointerException but we already checked it had a next line.
            */
            lineFromFile = scanner.nextLine().trim();
            /* I assumed you were looking for an exact match
             * because otherwise e.g. Bob and Bobby look the same
             * also equalsIgnoreCase allows me to ignore the case
            */
            if(lineFromFile.equalsIgnoreCase(name)) {
                scanner.close();
                System.out.println("I found " + name);
                return name; // The return keyword lets you send something back
            }
        }
        scanner.close();
    }
}

您可能还想考虑使用BufferedReader而不是扫描仪,当您想要读取一些行时,更多地使用扫描仪,例如,如果您尝试读取代码文件或书籍。特别是当您想要阅读许多类型的数据或正则表达式时。对于只读取整行文本,只需一个包装文件阅读器的缓冲读取器就更好了。我把它留下来是因为扫描仪确实工作,它可能会慢一点,但我怀疑速度是你的一个问题。作为参考,虽然这里有一个article如何做。

您也可以使用try-finally block或者如果您能够使用至少Java 7 try with resources block来确保关闭扫描程序,无论发生什么。我没有把它包括在内,因为它不是你问题的一部分,但是对于大型程序,这些结构非常有用并且会简化你的代码。