在密码学中有个简单的分析密码的方法,就是计算每个字母出现的频率,这个小程序就是计算输入字符串中每个字母出现的次数的,我现在初学java,我将把我平时的小练习发到这里,用来自勉和初学者共同学习进步.高手不要见笑.
//6.7.5
import java.io.bufferedreader;
import java.io.inputstreamreader;
public class analyser
{
private string words;
public analyser (string input)//构造方法,把输入的密码全部转换为大写字母
{
words = input.touppercase();
}
public int getnum()//返回密码的长度
{
return words.length();
}
public int result(char c)//方法:计算在密码中character c出现的次数
{
string temp=new string(words);
int index=temp.indexof(c);
int n=0;
while(index>=0)
{
temp=temp.substring(index+1,temp.length());
index=temp.indexof(c);
n++;
}
return n;
}
public static void main(string[] args)//主方法
{
system.out.print("please input the words:");//输入passwd
string inputline;
try{
bufferedreader in = new bufferedreader(new inputstreamreader(system.in));
inputline = in.readline();
}catch(exception exc)
{
system.out.println("sorry,please input a string,thx");
return;
}
analyser word=new analyser(inputline);//用类生成一个对象word
int[] num = new int[26];//定义一个字母,用来装a-z26个字母
int i;
char ch='a';
for (i=0;ch<91;ch++,i++)//计算每个字母在passwd出现的次数
num[i]=word.result(ch);
system.out.println("the passwd you input is : "+inputline);//输出
system.out.println("the length of the passwd is : "+word.getnum());//输出输入密码长度
for (i=0,ch='a';i<26;ch++,i++)//输出每个字母出现的次数
system.out.println("the num "+ch+" has presented : "+num[i]);
}
}
闽公网安备 35060202000074号