编写算法,统计一个字符串中出现的大写字母、小写字母、数字和其他字符出现的个数。

import java.util.Scanner;

public class Test2 {
    public static void main(String[] args) {
        //局部变量使用前一定要初始化
        int lowCount = 0,upperCount=0,numCount=0,otherCount=0;
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入字符串:");
        String str=sc.next();
        char[] chars=str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if(97<=chars[i]&&chars[i]<=122){
                //小写字母
                lowCount++;
            }
            else if(65<=chars[i]&&chars[i]<=90){
                upperCount++;
            }
            else if(48<=chars[i]&&chars[i]<=57){
                numCount++;
            }
            else{
                otherCount++;
            }
        }
        System.out.println("大写字母个数:"+upperCount);
        System.out.println("小写字母个数:"+lowCount);
        System.out.println("数字个数:"+numCount);
        System.out.println("其他字符个数:"+otherCount);
    }
}

猜你喜欢

转载自www.cnblogs.com/iceywu/p/11978628.html