1221: 单词统计问题

题目

Description

巨硬公司(huge-hard)最近计划出品一个字处理软件。软件基本功能已经完成,但还缺少一个单词统计的功能,你的任务就是为该公司写一段程序,完成统计功能。

需要统计的信息有两项:出现单词的个数和单个单词出现的次数。
Input

输入为一行字符串,即要统计的文本。
Output

输出由若干行组成,第一行是一个整数,表示单词的个数,从第二行开始,每行由字符串、冒号、整数组成,其中字符串是一个出现在文本中的单词,整数则是该单词在文本中出现的次数。
Sample Input

to know everything is to know nothing
Sample Output

7
everything:1
is:1
know:2
nothing:1
to:2


代码块

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cn = new Scanner(System.in);
        String str = cn.nextLine();
        String[] dd = str.split(" ");
        System.out.println(dd.length);
        Word[] word = new Word[dd.length];
        int k = 0;
        for (int i = 0; i < dd.length; i++) {
            if (dd[i].equals("-1"))//用改值的方法,跳过重复的单词
                continue;
            else {
                String name = dd[i];
                int temp = 0;
                for (int j = i + 1; j < dd.length; j++) {
                    if (dd[i].equals(dd[j])) {
                        dd[j] = "-1";//将重复的字符串的值改成-1
                        temp++;
                    }
                }
                word[k]= new Word(temp+1,name);
                k++;
            }
        }
        for(int i =0;i<k;i++){
            for(int j = i+1;j<k;j++){
                if(word[i].getName().compareTo(word[j].getName())>0){
                    Word zz = word[j];
                    word[j] = word[i];
                    word[i] = zz;
                }
            }
        }
        for (int z = 0; z < k; z++) {
            System.out.println(word[z].getName() + ":" + word[z].getTemp());
        }
    }
}

class Word {
    private int temp;
    private String name;

    public Word(int temp, String name) {
        this.name = name;
        this.temp = temp;
    }

    public void setTemp(int temp) {
        this.temp = temp;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getTemp() {
        return this.temp;
    }

    public String getName() {
        return this.name;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值