java项目作业_java工程项目作业1
发布日期:2021-06-24 16:40:45 浏览次数:2 分类:技术文章

本文共 1930 字,大约阅读时间需要 6 分钟。

用户需求:英语的26 个字母的频率在一本小说中是如何分布的?某类型文章中常出现的单词是什么?某作家最常用的词汇是什么?《哈利波特》 中最常用的短语是什么,等等。

要求:输出单个文件中的前 N 个最常出现的英语单词,并将结果输入到文本文件中。

我按照老师要求把整个程序分成了三部:

第一步:文件生成

import java.io.*;

public class MyFileOutput {

public static void main (String argv[]){

FileInputStream fin;

FileOutputStream fout;

int ch;

try{

fin=new FileInputStream(FileDescriptor.in);

fout=new FileOutputStream("zhong.txt");

System.out.println("请输入一行字符:");

while((ch=fin.read())!='\r')fout.write(ch);

fout.close();

fin.close();

System.out.println("文件写入成功!");

}

catch(FileNotFoundException e){

System.out.println("不能创建文件");

}

catch(IOException e){

System.out.println("输入流有误!");

}

}

}

第二步:查单词

import java.util.*;

public class CountWord {

public static String[] strTostrArray(String str) {

str = str.toLowerCase();// 将字符串中的英文部分的字符全部变为小写

String regex = "[\\W]+";// 非字母的正则表达式 --\W:表示任意一个非单词字符

str = str.replaceAll(regex, " ");

String[] strs = str.split(" "); // 以空格作为分隔符获得字符串数组

return strs;

}

public static void countword(String[] strs) {

HashMap strhash = new HashMap();

Integer in = null;// 用于存放put操作的返回值

for (String s : strs) {// 遍历数组 strs

in = strhash.put(s, 1);

if (in != null) {// 判断如果返回的不是null,则+1再放进去就是出现的次数

strhash.put(s, in + 1);

}

}

Set> entrySet = strhash.entrySet();

String maxStr = null;// 用于存放出现最多的单词

int maxValue = 0;// 用于存放出现最多的次数

for (java.util.Map.Entry e : entrySet) {

String key = e.getKey();

Integer value = e.getValue();

if (value > maxValue) {

maxValue = value;

maxStr = key;

}

}

第三步:文件导入

import java.io.*;

public class TypeFile {

public static void main(String args[]){

FileInputStream fin;

FileOutputStream fout;

int ch;

if(args.length<1){

System.out.println("请指定文件名");

return;

}

try{

fin=new FileInputStream(args[0]);

fout=new FileOutputStream(FileDescriptor.out);

while((ch=fin.read())!=-1)

fout.write(ch);

fin.close();

fout.close();

}

catch(FileNotFoundException e){

System.out.println("文件没找到");

}

catch(IOException e){

System.out.println("读入文件有误!");

}

}

转载地址:https://blog.csdn.net/weixin_33910305/article/details/114307561 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:power指令集 mysql_32位PowerPC常用指令集总结
下一篇:java 异常后重新执行_在Java中引发异常后继续执行

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月18日 09时44分22秒