簡體   English   中英

從文件中搜索字符串,並在 java 中返回該字符串?

[英]Searching for a string from file, and returning that string in java?

我對 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 (你目前所做的)。 在開始之前檢查是否循環讀取您的文件。

其次,在您閱讀並檢查所有行之前,您不知道您的文件不包含name ,僅僅因為您的單詞不在第一行並不意味着它不在第二行或第三行。 您需要閱讀完整內容打印name not found但仍未找到它。

我知道這已經得到了一些答案,但我想你可能會喜歡一個帶有評論的答案來解釋正在發生的事情。 我還用更常見的 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 而不是掃描儀,當您想要讀取行的位時,更會使用掃描儀,例如您正在嘗試閱讀代碼文件或書籍。 特別是當您想要讀取大量類型的數據或正則表達式時。 對於僅閱讀整行文本,僅緩沖閱讀器包裝文件閱讀器更好。 我忽略了這一點,因為掃描儀確實可以工作,它可能會更慢,但我懷疑速度是否是您的問題。 供您參考,但這里有一篇關於如何操作的文章

您也可以使用try-finally 塊,或者如果您能夠使用至少 Java 7 的try with resources 塊來確保無論發生什么都關閉掃描器。 我沒有包括它,因為它不是您問題的一部分,但對於較大的程序,這些結構非常有用,可以簡化您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM