zoukankan      html  css  js  c++  java
  • 2019年11月4日课堂测试,文本读入统计单词数2

    一、题目

     二、源代码

    import java.io.*;
    import java.util.*;
    
    
    public class ReadWord2 {
        private static String str1;
        private static String [] Str=new String[20000];
        private static int [] n=new int [20000];
        
        public static void main(String [] args) throws IOException {
            int num=0,i=0,j=0;
            double sum=0;
            Scanner input =new Scanner(System.in);
            
            File file =new File("src/Harry.txt");
            
            String get=null;
            BufferedReader reader =new BufferedReader(new FileReader(file));
            while((get=reader.readLine())!=null) {
                
                StringTokenizer sc =new StringTokenizer(get,",.?''\" -"); 
                while(sc.hasMoreElements()) {
                    str1=(String)sc.nextElement();
                    str1=str1.toLowerCase();
                    for(i=0;i<=num;i++) {
                        if(str1.equals(Str[i])) {
                            n[i]++;
                            break;
                        }
                    }
                    if(i>num) {
                        Str[num]=str1;
                        n[num]=1;
                        num++;
                    }
                }
            }
            
            for(i=0;i<num;i++) {
                for(j=i;j<num;j++) {
                    if(n[i]<n[j]) {
                        int temp=n[i];
                        n[i]=n[j];
                        n[j]=temp;
                        String tp=Str[i];
                        Str[i]=Str[j];
                        Str[j]=tp;
                    }
                    
                }
            }
            i=0;
            while(n[i]!=0) {
                sum+=n[i];
                i++;
            }
            System.out.println("单词总数为"+sum);
            System.out.println("请输入你想要查询的数量前几的单词数");
            int N=input.nextInt();
            for(i=0;i<N;i++) {
                System.out.print("第"+(i+1)+"多的单词是      "+Str[i]+"  共  "+n[i]+"  个  ");
                System.out.print("占全部单词的");
                System.out.printf("%.2f",n[i]*100/sum);
                System.out.println("%");
            }
            
            
        }
        
        
        
        
        
    }

    三、心得

      刚开始真是一点思路也没有,因为需要将从文件中把每一个单词分出来,这个是我当时头疼的地方。然后之后借鉴别人的代码发现了一个很棒的方法 StingTokenizer,可以将一个字符串按照自定义的符号分割成字符串,然后存储。然后还学到了BufferedReader是缓冲流,虽然不是必须的,但是可以加快读取的速度。  

  • 相关阅读:
    jquery 序列化form表单
    nginx for windows 安装
    nodejs idea 创建项目 (一)
    spring 配置 shiro rememberMe
    idea 2018 解决 双击shift 弹出 search everywhere 搜索框的方法
    redis 在windows 集群
    spring IOC控制反转和DI依赖注入
    redis 的安装
    shiro 通过jdbc连接数据库
    handlebars的用法
  • 原文地址:https://www.cnblogs.com/suanai/p/11795114.html
Copyright © 2011-2022 走看看