Java 运行检查文本文件中字符串的程序的适当方式是什么?

Java 运行检查文本文件中字符串的程序的适当方式是什么?,java,string,count,text-files,word-count,Java,String,Count,Text Files,Word Count,我必须制作一个程序来搜索一个特定的字符串,用户使用扫描仪在文本文件中输入该字符串,并返回该字符串在文本文件中使用的次数。虽然我尝试了无数种方法来解决这个问题,但最终程序还是在运行,但它向我询问了两次输入,结果总是只得到1。我做过它,所以它已经成为一个方法,但我不确定如何运行这个方法,因为它确实调用了用户选择的文本文件和字符串。这就是我到目前为止的想法: import java.util.*; import java.io.*; import javax.swing.*; import java.

我必须制作一个程序来搜索一个特定的字符串,用户使用扫描仪在文本文件中输入该字符串,并返回该字符串在文本文件中使用的次数。虽然我尝试了无数种方法来解决这个问题,但最终程序还是在运行,但它向我询问了两次输入,结果总是只得到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;
    }
}
这是我试图调用的文本文件的内容 嗨你好再见嗨你好再见嗨你好再见嗨你好再见嗨你好再见嗨你好再见嗨你好再见嗨你好再见嗨你好再见

如果您发现了代码中我可能遗漏的任何错误,请告诉我,非常感谢您的帮助。

您的问题是,如果您发现了一行匹配的代码,您就会中断;循环。因此,您的计数器永远不会超过1

相反,你应该去掉这个破口;从您的代码中,while循环将在所有行中运行

编辑:

以下代码已经过测试,可以正常工作。总的来说,值得注意的是:

A.主类是第一个加载的类,因此必须在程序开始时运行您想要运行的任何东西。主类也必须是静态的

B.我已将您使用的扫描仪改为BufferedReader和FileReader。这些是不同的类,也用于读取文件内容

C.我的while循环只会中断;当它到达文件的末尾时。如果在此之前中断,它将停止搜索,无法找到所有出现的情况

我不知道你到底想找什么。例如,如果您希望查找与您的单词相等的整行或包含您的单词的整行,等等。如果您更具体地告诉我您希望如何优化搜索,我可以更新代码

//在打包时,如果不导入整个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;
    }

如果您中断了while循环,那么while循环将从中转义。好吧,这肯定是一个问题:publicstaticvoidmainstring[]args{}也会更正您的缩进,这样您和我们就可以看到预期的流。现在,在@HovercraftFullOfEels编辑您的帖子之后,您应该能够看到循环在一次迭代后无条件地中断,您到底被卡在哪里了?你用调试器了吗?如果是,问题在哪里?如果没有,为什么不呢?我将投票结束这个问题,因为这不是一个请在我的代码站点中查找错误的问题。你必须说出你遇到了什么问题,并提出一个更具体的问题。考虑到主要方法中没有任何内容,我怀疑它是否有效。正确。我已经编辑过了。我相信用户有更多他没有发布的代码。我对如何运行此方法感到困惑,我尝试使用此方法,但没有任何问题,我会让它工作,然后张贴代码,这可能需要一些时间minutes@user3663055:您的问题表明您需要阅读/学习基础Java教科书或教程,因为您缺少如何使用该语言的基本概念。为了您自己的利益,请离开本网站,学习基础知识,因为它们将比让我们为您编写代码或尝试教您本网站不适合做的事情更好。