计算一段英文里的单词出现次数
package Letter;
import java.util.Scanner;
public class frequency {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String[] allWord = str.split(" |,|.");
int []letter1 = new int[allWord.length];//定义存储单词出现次数
//比较计数
int i = 0;
for(i = 0 ; i < allWord.length ; i++)
{
int k = 1;//计数单词出现次数
if( i > 0 )
{
int j;
for(j = 0 ; j < i ;j++)//判断单词是否重复
{
if(allWord[i] == allWord[j]) k = k + 1;
}
}
letter1[i] = k;
}
//根据单词出现数量给单词数组和计数数组排序
for(i = 0 ; i < allWord.length ; i++)
{
int p;
String p1;
int m;
for(m = i ; m < allWord.length ; m++)
{
if( letter1[i] < letter1[m])
{
p1 = allWord[i];//更改单词位置
allWord[i] = allWord[m];
allWord[m] = p1;
p = letter1[i];//更改数的位置
letter1[i] = letter1[m];
letter1[m] = p;
}
}
}
//输出
System.out.print("请输入需要输出前几位次数多的单词:");
Scanner scanner1 = new Scanner(System.in);
int n = scanner1.nextInt();
for(i = 0 ; i < n ; i++)
{
System.out.print(allWord[i]+" ");
}
}
}