【问题标题】:Java - Method that Prompts the User to Enter a FileJava - 提示用户输入文件的方法
【发布时间】:2014-05-07 10:55:35
【问题描述】:

我正在尝试编写一种方法,提示用户输入一个存储每个单词的文件,然后计算单词的频率。

问题是我想为这个方法使用一个固定大小为 1000 的数组。我已经在类中声明了一个字符串数组——String [] words = new String [1000];但是,我不确定如何将其集成到此方法中以保存文件的每个单词。任何 cmets 将不胜感激!

这是我目前所拥有的:

public static void inputFile() throws Exception
{
        java.io.File file = new java.io.File("123.txt");      
        try 
        {
            Scanner input = new Scanner(file);   
            while (input.hasNextLine()) 
            {
                String list = input.next();
                System.out.println(list);
            }
            input.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


}

【问题讨论】:

    标签: java file word frequency


    【解决方案1】:

    您不需要将文件的内容保存到对象中。 通过查看JavaDocs,您可以看到Scanner的方法支持正则表达式。

    只需阅读和搜索:

    File file = new File("file.txt");
    
    Scanner scanner = null;
    try
    {
        scanner = new Scanner(file);
    }
    catch (FileNotFoundException e){}
    
    int i = 0;
    while(scanner.hasNext("word"))
    {
        scanner.next("word");
        i++;
    }
    
    System.out.println(i +" occurances of the word 'word'");
    

    【讨论】:

    • 那么,我不必为这个方法传递一个数组作为参数?
    • 嗯,你想计算一个单词的出现次数,你只需要在我的例子中改变你正在搜索的单词。
    【解决方案2】:

    数组是错误的结构。您需要一个 HashMap 来保存每个单词的当前计数。您获取一个单词的当前计数,将 null 更改为 0,然后加 1 并将其放回地图中。您可以根据需要将其修剪到 1000 以上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 2013-04-30
      • 2012-03-30
      相关资源
      最近更新 更多