Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从文件中搜索字符串,然后用java返回该字符串?_Java_String_File - Fatal编程技术网

从文件中搜索字符串,然后用java返回该字符串?

从文件中搜索字符串,然后用java返回该字符串?,java,string,file,Java,String,File,我对Java还是相当陌生,但我一直在尝试让我的程序让用户输入一个名称并在文件中搜索该名称,如果该名称在文件中,它将返回到main。如果该名称不在文件中,程序将要求用户输入另一个名称,直到他们输入文件中的名称为止。如果用户输入“退出”,程序将退出。我有一些代码不能完成我想要的,但我希望它能让我的观点得到理解 public static String getName(File inFile, Scanner console) throws FileNotFoundException {

我对Java还是相当陌生,但我一直在尝试让我的程序让用户输入一个名称并在文件中搜索该名称,如果该名称在文件中,它将返回到main。如果该名称不在文件中,程序将要求用户输入另一个名称,直到他们输入文件中的名称为止。如果用户输入“退出”,程序将退出。我有一些代码不能完成我想要的,但我希望它能让我的观点得到理解

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;
}

在下面的代码中,我们有一个外循环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;
}

好吧,您的循环已经完全中断了,首先,您不想检查用户是否在文件的每一行都写了
quit
(您当前所做的)。在开始ro读取循环中的文件之前,请进行检查


第二,在阅读并检查所有行之前,您不知道您的文件不包含
name
,因为您的单词不在第一行并不意味着它不在第二行或第三行。你需要打印
找不到的名字
,在你阅读完之后,仍然没有找到它。

我知道这已经有了一些答案,但我想你可能会喜欢一个带有注释的答案来解释更多的事情。我还用更常见的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();
    }
}

您可能还想考虑使用BuffeDeRe读器而不是扫描仪,扫描器在读取线段时更常用,例如,如果您试图读取代码文件或书籍。特别是当您想要读取大量类型的数据或正则表达式时。对于只读取整行文本而言,使用缓冲读取器包装文件读取器更好。我忽略了这一点,因为扫描仪确实可以工作,它可能会慢一些,但我怀疑在你的情况下速度是一个问题。不过,这里有一个关于如何做的示例,供您参考


如果您至少能够使用Java7a来确保无论发生什么情况,都可以使用或来确保关闭扫描仪。我没有包括这一点,因为这不是您问题的一部分,但对于较大的程序,这些构造非常有用,并将简化您的代码。

您的输入文件每行包含一个名称?您是否已使用System初始化控制台扫描程序。在?您需要嵌套循环,代码需要具有与您希望的结构相匹配的结构。是,主要方法是使扫描仪初始化,而你的while循环相当混乱。每次查看文件中的新行时,您都试图更改要查找的名称。您可能需要检查文件中的所有名称,然后才能确定尚未找到该文件并提示输入另一个名称。