运行 在文本文件中检查字符串的程序的正确方法是什么?

What is the appropriate way to run a program that checks for a string inside of a text file?

我必须制作一个程序来搜索特定的字符串,用户使用扫描仪在文本文件中输入该字符串,并且 returns 该字符串在文本中被使用的次数文件。在尝试以无数种方式解决问题时,我以某种方式结束了程序 运行ning,但它要求我输入两次,但总是只返回“1”。我研究过它,因此它已成为一种方法,但我不确定如何 运行 这种方法,因为它确实调用了用户选择的文本文件和字符串。这是我到目前为止想出的:

import java.util.*;
import java.io.*;
import javax.swing.*;
import java.lang.*;

public class WordCount 
{


    public static int countWord(File dataFile, String WordToSearch) throws FileNotFoundException 
{
        int count = 0;
        dataFile = new File("text.txt");
        Scanner FileInput = new Scanner(dataFile);
        while (FileInput.hasNextLine()) 
{
            Scanner s = new Scanner(System.in);
            String search = s.next();
            if (search.equals(WordToSearch))
                count++;

        }
        return count;
    }
}

这是我要调用的文本文件的内容 "Hi Hello Goodbye Hi Hello Goodbye Hi Hello Goodbye Hi Hello Goodbye Hi Hello Goodbye Hi Hello Goodbye Hi Hello Goodbye"

如果您发现我在代码中遗漏的任何错误,请告诉我,非常感谢您提供的所有帮助。

您的问题是 if 您找到了与您匹配的行 break; 循环。因此,您的计数器永远不会超过 1。

相反,您应该从代码中删除 break;,然后 while 循环将 运行 遍历所有行。

编辑:

以下代码已经过测试并且可以工作。值得注意的总体要点是:

A. 主要 class 是第一个 class 加载因此必须 运行 任何你想要的 运行 在节目开始时。另外主要 class 必须是静态的。

B. 我已经将您使用的 Scanner 更改为 BufferedReaderFileReader 它们是不同的 classes 也被设计用来读取文件内容。

C. 我的 while 循环仅在 breaks; 到达文件末尾时。如果您 break 之前,它将停止搜索查找所有匹配项。

D. 我不知道你到底想找什么。例如,如果你想找到等于你的单词的整行或包含你的单词的整行等(如果你更具体地告诉我你想如何优化你的搜索,我可以更新代码)

// 如果不导入整个 java 包,打包时会严重减小程序的大小 // 在这里,我已经缩小了 io* 和 util* 的范围,使其成为您真正需要的东西

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ScannerInt {

    public static void main(String[] args) {
        // the main method is the first that is run.
        // the main method MUST be static
        // inside the main method put whatever you want to run in your program

        scan(); // we run the scanner method which is created below
    }

    public static void scan() {
            // first i create a scanner so that the java command prompt can take input
            Scanner input = new Scanner(System.in);

            System.out.println("Enter file path to file and file name: "); //prompt the reader to type the file directory and name
            File file = new File(input.nextLine()); // determine what file they want based on that name

            System.out.println("Enter the line you want to find: "); //prompt the reader to type the line they want to count
            String line = input.nextLine(); // determine what line they want based on that string

            // this statement tells them how many occurances there are
            // this is done by the countWord() method (which when run returns a integer)
            System.out.println("There are " + countWord(file, line) + " occurances.");

            System.exit(0); // ends the program
    }

    // the countWord method takes a file name and word to search and returns an integer
    public static int countWord(File dataFile, String WordToSearch) {

        int count = 0; // start are counter

        // NOTE: i prefer a BufferedReader to a Scanner you can change this if you want

        // load the buffered reader
        BufferedReader FileInput = null;
        try {
            // attempt to open the file which we have been told about
            FileInput = new BufferedReader(new FileReader(dataFile));
        } catch (FileNotFoundException ex) {
            // if the file does not exist a FileNotFoundException will occur
            Logger.getLogger(ScannerInt.class.getName()).log(Level.SEVERE, null, ex);
        }

        // then try searching the file
        try {
            // this while loop runs forever until it is broken below
            while (true) {
                String search = FileInput.readLine(); // we read a line and store it

                if (search == null) { // if the line is "null" that means the file has ended and their are no more lines so break
                    break;
                }

                // then we check if this line has the text

                // NOTE: i do not know what exactly you want to do here but currently this checks if the entire line
                // is exactly equal to the string. This means though that if their are other words on the line it will not count

                // Alternatively you can use search.contains(WordToSearch)
                // that will check if the "WordToSearch" is anywhere in the line. Unfortunately that will not record if there is more than one

                // (There is one more option but it is more complex but i will only mention it if you find the other two do not work)
                if (search.equals(WordToSearch)) {
                    count++;
                }
            }
        } catch (IOException ex) {
            // if the line it tries to read does not exist a IOException will occur
            Logger.getLogger(ScannerInt.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            FileInput.close(); // close the file reader
        } catch (IOException ex) {
            // if the FileInput reader has broken and therefore can not close a IOException will occur
            Logger.getLogger(ScannerInt.class.getName()).log(Level.SEVERE, null, ex);
        }

        return count;
    }