在密碼學中有個簡單的分析密碼的方法,就是計算每個字母出現的頻率,這個小程序就是計算輸入字符串中每個字母出現的次數的,我現在初學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]);
}
}
新聞熱點
疑難解答