java项目作业_java工程项目作业1

用户需求:英语的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("读入文件有误!");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值