碰巧要做这个作业的同学低调地参考一下
public class TextAnalyser {
private int total=0;
private int[] charCount = new int[26]; //this array stores number of chars
public TextAnalyser()
{
}
public TextAnalyser(String initial)
{
this.analyse(initial);
}
public void analyse(String str)
{
//restore all chars to lower case
str = str.toLowerCase();
//index of current letter
int index = 0;
//letters number
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(Character.isLetter(ch))
{
total++;
}
}
//count the char number
for(char charInitial = 'a';charInitial<=(char)('a'+25);charInitial++)
{
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(charInitial==ch)
{
charCount[index]++;
}
}
index++;
}
}
public int charsAnalysed()
{
return total;
}
public int frequency(char c)
{
c = Character.toLowerCase(c);
return charCount[getCharIndex(c)];
}
public double percentage(char c)
{
c = Character.toLowerCase(c);
double percentage = 0.0;
if(total==0||frequency(c)==0)
return 0.0;
percentage = (double)frequency(c)/total*100;
return percentage;
}
public char mostFrequent()
{
if(total==0)
return '?';
int maxCount=0;
int index = 0;
char mostFrequentChar = '?';
for(char charInitial = 'a';charInitial<=(char)('a'+25);charInitial++)
{
if(charCount[index]>=maxCount)
{
maxCount=charCount[index];
mostFrequentChar=charInitial;
}
index++;
}
return mostFrequentChar;
}
public void clear()
{
total = 0;
charCount = new int[26];
}
//private helper methods
//return the index of given char of charCount array
private int getCharIndex(char ch)
{
return ch-'a';
}
}