设有一个文本文件word01.txt,内容如下:
after a minute or two and said to his friend he opened them again
a minute or two and said to
friend he opened them again
and closed and to his
编写程序,统计文件中每个字母出现的次数。
输出示例如下
{ =27, a=13, c=1, d=11, e=14, f=3, g=2, h=6, i=10, l=1, m=4, n=12, o=10, p=2, r=5, s=5, t=10, u=2, w=2}
这个题目原本是java大数据的一道经典例题——统计单词数,今天装好开发环境后想写一个程序试试手,就选了这个题目,审题不仔细,写完才发现写错了。但也将错就错了,毕竟两个代码差异不算太大。
读取文件
这个例题的核心点就两个,一个是读取文本文件,一个是统计。读取文本文文件就不详解了,直接从网上找的。代码如下:
class FileTools {
/*
* 调用时传递文本文件的路径
* 读取文本内容,按行读取,返回文本字符串
* */
public String readFile(String pathname) {
File file = new File(pathname);
String text = "";
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(pathname);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str = null;
while ((str = bufferedReader.readLine()) != null) {
// text = text + str + "\n"; //保留换行
text = text + str; //不保留换行
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
}
HashMap
HashMap存储的内容是键值对(key-value)映射,在进行数据存储时可以标记成 字符:数量 的形式。在本例子中HashMap的使用方式如下:
Map<String, Integer> map = new HashMap<String, Integer>();
别问为什么不用 int,HashMap 中的元素实际上是对象,一些常见的基本类型要使用它的包装类。
附上其对照表:
基本类型 | 引用类型 |
---|---|
boolean | Boolean |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
在写其他项目时按需要选择即可。
在添加元素时,HashMap会保证key的唯一性,不会重复添加key,所以在统计时,可以先使用get方法取出要累加字符的当前数量,+1后重新put就可以。当然,如果HashMap中还没有的元素,get会得到一个null。所以,还要提前写一个if,如果得到的是null,重新赋值为0.
这一部分的代码单独拿出来让各位注意下:
count = map.get(String.valueOf(text.charAt(i))); //String.valueOf将char转为字符转
if (count == null)
count = 0;
count++;
map.put(String.valueOf(text.charAt(i)), count);
然后就不多废话,全部代码如下
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class test {
public static void main(String[] args) {
String pathname = "files/word01.txt";
String text = "";
Integer count = 0; //与HashMap的Integer对应
FileTools file_tools = new FileTools(); //调用类,读取文本
text = file_tools.readFile(pathname);
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < text.length(); i++) {
count = map.get(String.valueOf(text.charAt(i)));
if (count == null)
count = 0;
count++;
map.put(String.valueOf(text.charAt(i)), count);
}
System.out.println(map);
}
}
class FileTools {
/*
* 调用时传递文本文件的路径
* 读取文本内容,按行读取,返回文本字符串
* */
public String readFile(String pathname) {
File file = new File(pathname);
String text = "";
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(pathname);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str = null;
while ((str = bufferedReader.readLine()) != null) {
// text = text + str + "\n"; //保留换行
text = text + str; //不保留换行
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
}
如有错误,欢迎指正。