Java automatically judges the number of occurrences of words in a file

Article Directory

foreword

Attention to detail

full code

summary


foreword

        I learned java from my tutor, recently learned about HashMap in Map, and know its various usages. Now let’s make a small program to quickly calculate the number of words in a txt file.

Detailed explanation of HashMap

 

         We can see that HashMap is inherited from Map, so it has all the methods of Map. The most commonly used methods in HashMap include:

  • put(key, value): Add key-value pairs to HashMap.
  • get(key): Get the value corresponding to the specified key.
  • remove(key): Delete the key-value pair corresponding to the specified key.
  • containsKey(key): Determine whether the HashMap contains the specified key.
  • keySet(): Returns the Set collection composed of all keys in the HashMap.

Attention to detail

        HasHmap is unordered and non-repetitive. If you want to store repeated data, you should use a list collection. For other details, please refer to my guide (76 messages) [JAVA advanced] Set collection, Map collection Blog-CSDN Blog

full code

public class ReadFileConut {
    public static void main(String[] args) {
        try {
            RandomAccessFile file = new RandomAccessFile("E:/Java项目文件夹/JavaG/MultitHreading/src/csdn528/CountFile.txt", "r");
            HashMap<String,Integer> contF = new HashMap<String,Integer>();
            String str;
            while ((str = file.readLine()) != null) {
                String []words=str.split(",");//分割字符串
                int i=1;
                for(String word:words){//遍历字符串数组
                    word=word.toLowerCase();//将单词转换成小写
                    //判断集合中是否已存有不区分大小写的相同字符串,同时判断字符串是否是空串
                    if(!contF.containsKey(word)&&!word.equals(""))
                    {//将字符串存储到集合中
                        System.out.println("出现的单词有:"+word);
                        contF.put(word,i);
                    }
                    else {
                        i++;
                        contF.put(word,i);
                    }
                }
            }
            System.out.println("此句子共出现"+contF.size()+"个单词。");
            System.out.println("每个单词的个数为:"+contF);
            //将读取到的数据输出到控制台
            file.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }}

 The code and comments are shown in the figure, you can see it after a few more

summary

        The road to Java is long, although the road is long and difficult, but the journey will come!

Guess you like

Origin blog.csdn.net/qq_51294997/article/details/130918232