zoukankan      html  css  js  c++  java
  • 工程项目作业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]+"	"+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();
        }
    }

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

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

  • 相关阅读:
    jquery--blur()事件,在页面加载时自动获取焦点
    jquery三级联动
    工具集
    兼容各个浏览器:禁止鼠标选择文字事件
    jquery 事件委托(利用冒泡)
    小功能1:多种方法实现网页加载进度条
    JavaSE| 泛型
    SSM整合
    Redis数据库 02事务| 持久化| 主从复制| 集群
    Hadoop| MapperReduce02 框架原理
  • 原文地址:https://www.cnblogs.com/gothic-death/p/9775841.html
Copyright © 2011-2022 走看看