容器类既是类,又是存储类的容器。作为容器来讲,它存放多个“类对象”;作为类来讲,它能够对存放于其中的“类对象”进行操作。
我这里涉及到LInkedList、HashMap、HashSet等类的使用。
1.题目介绍
-
用封装LinkedList的方式实现一个Stack容器。
-
用LinkedList实现一个类,该类有一个方法,该方法接受一个字符串作为参数,依次读取字符串中的字符,每次遇到“+”时就将“+”后面的一个字符压入栈内,每次遇到“-”时就将当前栈顶的字符弹出并在控制台打印,直至字符串遍历完,最后输出栈上剩余内容。实现main()方法调用这个方法,并输出字符串"+U+n+c- - -+e+r+t- - -+a-+i-+n+y- - -+ -+r+u–+l+e+s- - -",观察输出。
-
从一个文件中读入语句,并进行词频统计。进一步改写程序,统计文件中Java关键字出现频率,在统计时,创建一个Set存储所有的Java关键字,在判断一个字符串记号是否为关键字时访问该Set。
2.题目分析
-
第一题:
java中的stack接口已经废弃不用,原因可能是其他接口类(比如我们要说到的LInkedList)完全可以满足它的所有功能。
首先我们分析一下Stack接口该有的功能,最基本的操作是出栈(pop)和入栈(push),然后好像没什么可做了(滑稽)。咳咳,本着画蛇添足画龙点睛的精神,我这里再加入一个查看栈顶元素函数(peek)、一个判断栈是否空函数(isEmpty)和一个返回栈长函数(size)。
然后基本思路就是在Stack类中封装一个LinkedList对象实例,在默认构造方法内将LinkedList对象初始化,剩下对栈的操作直接调用LInkedList的方法就OK了。 -
第二题:
完全可以使用第一题写的Stack来做这个题,不过我没有用。
这里我定义了一个test_string方法来完成对输入字符串的测试,其参数为字符串(这个我们在main方法里读取输入获得),然后对每一个字符进行检验。共分为三种情况:‘+’、‘-’、其它字符。如果读取到‘+’,我们将下一个字符入栈并给计数变量i多加1以跳过对下一个字符的检验;如果读取到‘-’,出栈;如果读取到其他字符,我们什么也不做。这样的实现方案是完全依赖于用户输入的,因为我们假设用户不会输入连续的其他字符或者超额出栈(毕竟用户就是我呢),所以说程序并不健壮。 -
第三题:
这里要求我们对文件进行词频统计,并统计java关键词的出现频率。
先说说存储工具。
对于词频统计,键值对Map实在是最合适的工具了,由于没有额外要求,这里采用HashMap。然后使用一个HashSet对象存储所有的java关键字,判断是否为java关键字时调用contains方法。
然后我们说说文件输入和词语匹配。
我把文件所含字符串一整行一整行地传给StringTokenizer。
我使用Bufferedread类来完成文件读取,这个类的readline函数一次读取一整行,对于一般文件是符合要求的。然后关于词语匹配这个问题,我采用StringTokenizer类解决,它可以将字符串按指定的分隔符分成一个个的词语,这样我们就可以统计词频了:如果HashMap中不存在给定的词语,则将这个词语加入Map中并计数1;如果存在,则只要将对应的计数值+1即可。
统计完毕之后类中的Map会包含所有统计到的词语及其频度,接下来由两个打印函数来打印词频和java关键字频率。
如此这般,实现完毕!!!
3.代码实现
第一题:
import java.util.LinkedList;
import java.util.Random;
public class Stack<E>//E是类型参数,你把它与函数参数做类比就好理解了。注意:这里的E在java里定义的,代表集合元素Element。所以不能自定义类型参数。
{
private LinkedList<E> store;/封装一个LinkedList对象实例
public Stack(){
store=new LinkedList<E>();//初始化
}
public void push(E e){
store.addLast(e);//将元素添加在末尾就相当于入栈了
}
public E pop(){
return store.removeLast();//从末尾移除元素就相当于出栈了
}
public E peek(){
return store.getLast();
}
public boolean isEmpty(){
return store.isEmpty();
}
public int size(){
return store.size();
}
public static void main(String[] args){
System.out.println("*************测试stack容器类_START*****************");
Stack<Integer> s_int=new Stack<Integer>();
Random rand=new Random(34);
System.out.println("....正在向整数栈中压随机数....");
for(int i=0;i<20;i++){
s_int.push(rand.nextInt(40));
System.out.print(s_int.peek()+" ");
}
System.out.println("\n压栈完成,准备出栈");
for(int i=0;i<20;i++)
System.out.println("第"+(i+1)+"次出栈,出栈元素为:"+s_int.pop());
System.out.println("*************测试stack容器类_END*****************");
}
}
第二题:
import java.util.LinkedList;
import java.util.Scanner;
public class Test_LinList
{
private LinkedList<Character> stack_char;
public Test_LinList(){
stack_char=new LinkedList<Character>();
}
public void test_string(String s){
System.out.println("开始测试给定的字符串....");
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='+'){
stack_char.addLast(s.charAt(i+1));/入栈下一个字符
i+=1;//給计数变量i多加一,避免对下一个字符的检验(万一下一个字符是‘+’或‘-’呢?
}
else if(s.charAt(i)=='-')//出栈栈顶元素
System.out.println("pop栈顶元素:"+stack_char.removeLast());
else;
}
System.out.println("字符串已经遍历完成,开始打印栈中剩余的值");
while(!stack_char.isEmpty())
System.out.print(stack_char.removeLast()+" ");
System.out.println();
}
public static void main(String[] args){
String s=null;
Scanner sc=new Scanner(System.in);
System.out.print("请输入待测试的字符串:");
s=sc.nextLine();//读取用户输入字符串
Test_LinList t=new Test_LinList();
t.test_string(s);
sc.close();
}
}
第三题:
import java.io.*;
import java.util.*;
public class word_statistics
{
private File fd;//文件类
private Map<String,Integer> statistics;
private int count;//对文件中出现的词语总个数计数,为频率计算做准备
private static String[] key_set_str={"abstract","default","null","switch","boolean","do","if","package","nchronzed","break","double","implements","private","this","byte","else","import","protected","throw","throws","case","extends","instanceof","public","transient","catch","false","int","return","true","char","final","interface","short","try","class","finally","long","static","void","float","native","strictfp","volatile","continue","for","new","super","while","assert","enum"};
private static Set<String> key_set_of_java=new HashSet<String>();
public word_statistics(String fileName){//默认构造方法是要传入一个文件名作为参数的
fd=new File(fileName);
statistics=new HashMap<String,Integer>();
count=0;
for(String s:key_set_str)
key_set_of_java.add(s);//把java关键词加到Set里
}
public void work() throws FileNotFoundException,IOException{
String temp=null;
BufferedReader reader=new BufferedReader(new FileReader(fd));
while((temp=reader.readLine())!=null){//一行一行读取
StringTokenizer st=new StringTokenizer(temp,"{\r\n\t[0123456789]=\",+:\\;;.}(),<>-! *:");//分隔符自己加吧
while(st.hasMoreTokens()){
String key=st.nextToken();
count++;
if(statistics.get(key)!=null){//map里存在这个词语
statistics.put(key, statistics.get(key)+1);
}
else//map里不存在这个词语
statistics.put(key, 1);
}
}
reader.close();
}
public void print_statistics(){
System.out.println("这个文件里共有"+count+"个词语,结果打印如下:\n"+statistics+"\n");
}
public void print_key_of_java(){
System.out.println("开始打印java关键词出现频率....");
for(Map.Entry<String,Integer> item:statistics.entrySet())//遍历Map
if(key_set_of_java.contains(item.getKey()))
System.out.println("关键词“"+item.getKey()+"”的出现频率为:"+((double)item.getValue()/count));
}
public static void main(String[] args) throws FileNotFoundException,IOException{
word_statistics w=new word_statistics("TestMap.java");//我这里测试的文件是“TestMap.java"
System.out.println("开始统计词频....");
w.work();
System.out.println("统计完毕,输出统计结果!");
w.print_statistics();
w.print_key_of_java();
}
}
4.结果截图
第一题:
第二题:
第三题:
以下是测试输入文件“TestMap.java":
import java.util.*;
public class TestMap{
static String[] s=new String[4];
static {
s[0]="I have a dream that one day this nation will rise up, "
+ "live up to the true meaning of its creed: "
+ "\"We hold these truths to be self-evident; "
+ "that all men are created equal.\"";
s[1]="I have a dream that one day on the red hills of Georgia "
+ "the sons of former slaves and the sons of former slave-owners "
+ "will be able to sit down together at the table of brotherhood.";
s[2]="I have a dream that one day even the state of Mississippi, "
+ "a state sweltering with the heat of injustice, "
+ "sweltering with the heat of oppression, "
+ "will be transformed into an oasis of freedom and justice";
s[3]="I have a dream that my four children will one day live in a nation "
+ "where they will not be judged by the color if their skin "
+ "but by the content of their character.";
}
public static void main(String[] args){
Map<String,Integer> statistics=new HashMap<String,Integer>();
for(int i=0;i<s.length;i++){
StringTokenizer st=new StringTokenizer(s[i],",.;:-\" ");
while(st.hasMoreTokens()){
String key=st.nextToken();
if(statistics.get(key)!=null){
statistics.put(key, statistics.get(key)+1);
}
else
statistics.put(key, 1);
}
}
System.out.println(statistics);
}
}