方法:通過數組ArrayList實現
代碼包括兩個文件
1) 保存統計的字符和其出現次數的對象1
package codeSHP;
public class Object01 {
char c;
int count;
public Object01(char c, int count ){
this.c= c;
this.count=count;
}
}
2) 主程序
package codeSHP;
import java.util.ArrayList;
import java.util.Scanner;
//計算輸入的每個字符出現的次數
public class RateNum {
private void countNum(String str) {
ArrayList<Object01> al = new ArrayList<Object01>();
//System.out.println("size :"+al.size());
//Object01 obj = null;
for (int i = 0; i < str.length(); i++) { //將string拆成一個一個char類型的字符
char c = str.charAt(i);
int count = 1; //默認的出現的次數爲1
if(al.size()==0){ //輸入第一個字符
al.add(new Object01(c, count));
}else{ //每輸入一個新的字符都需要和前面的字符一一比較
int flag=0;
for(int j=0;j<al.size();j++){
Object01 obj1 = (Object01) al.get(j);
char c1 = obj1.c;
int count1 = obj1.count;
//System.out.println(c1 + " " + count1);
if(c==c1){ //如果該字符在數組中出現,將該字符對應的次數加1 ,更新該字符的數據,並跳出循環
count1++;
flag=1;
al.remove(obj1);
al.add(new Object01(c,count1));
break;
}
}
if(flag==0){ //如果以上循環沒有找到相同字符,將新的字符加入數組
al.add(new Object01(c,count));
}
}
}
//輸出結果
for (int k = 0; k < al.size(); k++) {
Object01 obj2 = (Object01) al.get(k);
System.out.println(obj2.c + " appear: " + obj2.count + " times ");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter string :");
String s = sc.nextLine();
new RateNum().countNum(s);
}
}
3) 運行結果: 空格也作了統計
Enter string :System.out.print("Enter string :");
S appear: 1 times
y appear: 1 times
m appear: 1 times
o appear: 1 times
u appear: 1 times
. appear: 2 times
p appear: 1 times
( appear: 1 times
E appear: 1 times
e appear: 2 times
s appear: 2 times
t appear: 5 times
r appear: 3 times
i appear: 2 times
n appear: 3 times
g appear: 1 times
appear: 2 times
: appear: 1 times
" appear: 2 times
) appear: 1 times
; appear: 1 times