java 单词出现次数_java语言 找出文章中出现次数最多的单词

这是一个Java程序,用于读取名为'word.txt'的文件并统计其中每个单词出现的次数。程序使用HashMap存储单词及其对应的计数,通过遍历文件内容,将单词拆分并更新计数。最后,程序找出出现次数最多的单词并打印出来。
摘要由CSDN通过智能技术生成

package english;

import java.io.File;

import java.util.Scanner;

import java.io.FileNotFoundException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Set;

public class Words {

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

File file=new File("E:\\word.txt"); //读取文件

if(!file.exists()){

System.out.println("文件不存在");

return;

}

Scanner scanner=new Scanner(file);

HashMap hashMap=new HashMap();

//System.out.println("文章-----------------------------------");

while(scanner.hasNextLine()) {

String line=scanner.nextLine();

//System.out.println(line);

String[] lineWords=line.split("\\W+"); //导入文章,但是被注释掉了

Set wordSet=hashMap.keySet();

for(int i=0;i

if(wordSet.contains(lineWords[i])) {

Integer number=hashMap.get(lineWords[i]);

number++;

hashMap.put(lineWords[i], number);

}

else {

hashMap.put(lineWords[i], 1);

}

}

}

//System.out.println("统计单词:------------------------------");

Iterator iterator=hashMap.keySet().iterator();

int max=0;

String maxword=null;

while(iterator.hasNext()){

String word=iterator.next();

//System.out.printf("单词:%-12s 出现次数:%d\n",word,hashMap.get(word));

if(hashMap.get(word)>max) { //比较出现次数最多的单词

max=hashMap.get(word);

maxword=word;

}

}

System.out.println("出现最多的是"+maxword);

System.out.println("最多出现了"+max+"次");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值