题目
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;
}
}