有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何从用户输入java中查找和打印文本文件中的重复单词

当我运行程序时,我想在文本文件中输入一个单词,并让它打印出单词在文本中存储了多少次。例如:

从文本中输入一个单词:eric

eric一词在文本文件中存储了5次

我下面的代码已经读取了文本文件,但我仍然坚持使用wordCount方法。我不知道怎么开始

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class WordSet {

    private static Scanner file;
    private static ArrayList<String> words = new ArrayList<String>();
    //private static Map<String, Integer> occurences = new HashMap<String, Integer>();
    //private static Set<String> uniqueWords = new HashSet<String>(words);
    //private static int tWords = 0;
    //private static int uWords = 0;

    //private static String [] word1 = new String[10];
    //private static String [] word2 = new String[10];

    public static void openFile() throws IOException {

        try {
            file = new Scanner(new File("words.txt"));

        } catch (FileNotFoundException e) {
            System.out.println("File Not Found");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("IOException");
        }
    }

    public static String wordCount() throws IOException {

        Random r = new Random();

        while(file.hasNext()) {
            words.add(file.next());
            }

        String wordCount = words.get(r.nextInt(words.size()));

        return wordCount;

    }

    public static void main(String[] args) throws IOException {

        System.out.println("Enter a word from the text: ");
        openFile();

        Scanner scan = new Scanner(System.in);

        String pickWord = wordCount();
        while(scan.hasNext()) {
            String input = scan.nextLine();

            if(input.equals(pickWord)) {
                System.out.println(pickWord);
            }
        }
        scan.close();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    我会考虑对文件中的每个词进行散列和计数。您也可以散列用户输入,如果它在表中,则返回计数。看起来你已经计划好了

  2. # 2 楼答案

    我已经添加了从命令行获取的输入,并读取了ArrayList,以给出下面的freq代码片段

    public static void main(String[] args) throws IOException {
        System.out.println("Enter a word from the text: ");
        openFile();
        Scanner scan = new Scanner(System.in);
        String inputStr = scan.next();
        Collections.frequency(words, inputStr);
        String pickWord = wordCount();
        System.out.println("You have entered '" + inputStr
                + "' frequency in text file is :"
                + Collections.frequency(words, inputStr));
        /*
         * while(scan.hasNext()) { String input = scan.nextLine();
         * 
         * if(input.equals(pickWord)) { System.out.println(pickWord); } }
         */
        scan.close();
    }
    

    Bu使用集合。frequency()u可以用更少的代码轻松计数…:)