创建一个长度为n[50,100]的字符数组,strs, 随机存入n个小写字母,然后统计每个字母出现的个数

public class Letter {
    public static void main(String[] args) {
        int n = (int)(Math.random()*51+50);
        char[] strs = new char[n];
        for(int i=0;i<strs.length;i++) {
            strs[i] = (char)(Math.random()*26+97);
        }
        for(int i=0;i<strs.length;i++) {//取出一个字母
            boolean bol = false;//标记为false
            int count = 1;
            for(int j=0;j<i;j++) {
                if(strs[i]==strs[j]) {//跟之前取过的字母进行判断,看看是否取过。
                    bol = true;//如果取过,将此字母改标记为true
                    break;//结束全部内层循环,重新取球。
                }
            }
            if(bol==true) {//标记为true,就结束这次外层循环,继续取下一个字母。下边的for循环就不用执行了。
                continue;
            }
            for(int j=i+1;j<strs.length;j++) {
                    if(strs[i]==strs[j]) {//取之前没有取过的球和之后的球相比有没有一样的,如果有就在count上+1
                        count++;
                    }
            }
            System.out.println(strs[i]+":"+count);
        }
    }
}
 

猜你喜欢

转载自blog.csdn.net/Betty_betty_betty/article/details/81268398