工程项目作业1

Statistics.java

import java.io.*;

public class Statistics {
    
    private String word="";
    private String[] str = new String[500];
    private int[] count = new int[500];
    private int i=0;        //统计现有单词的数量
    
    //读取文件内容
    public void readFile( String filename ){
        File file = new File( filename );
        Reader reader = null;
        try{
            reader = new InputStreamReader( new FileInputStream( file ) );
            int tempchar;
            while((tempchar = reader.read()) != -1 ){
                extractWord( tempchar );                            //传每个字符
            }
            reader.close();
        }
        catch( Exception e ){
            e.printStackTrace();
        }
    }
    
    //提取单词
    public void extractWord( int tempchar ){
        if( ((tempchar>65&&tempchar<90)||(tempchar>97&&tempchar<122)) ){    //tempchar为字母时,追加
            word += (char)tempchar;
        }
        else if((!"".equals(word))){
            statisticalWord();                                                //统计
            word="";
        }
    }
    
    //统计单词
    public int statisticalWord(){
        int j=0;
        for( ; j<i; j++ ){
            if( str[j].equals(word) ){
                count[j]++;                                            //计次加一
                return 0;
            }
        }
        str[j]=word;                                                //添加单词
        count[j]++;
        i++;
        return 0;
    }
    
    //将统计信息显示
    public void display(){
        for(int j=0; j<i; j++ ){
            System.out.println(str[j]+"\t"+count[j]);
        }
    }
    
}

Words.java

public class Words {
    public static void main( String [] args ){
        String filename = "C:/file.txt";
        Statistics sta = new Statistics();
        sta.readFile(filename);
        sta.display();
    }
}

思路就是先读取文件内容,通过空格和一些符号来分隔单词,存入一个临时的地方与已记录的单词进行比对,统计后输出。

中途遇到的一些问题:文件读入写出不怎么熟练,在提取单词的时候没有注意到空的字符串和空格也会被记录,以及尝试过将统计信息写入文件但是失败。

猜你喜欢

转载自www.cnblogs.com/gothic-death/p/9775841.html