每日作业20200611 - 统计代码中字符数量

题目

输入: 本程序代码
输出: 程序中有多少个字母, 多少个数字, 多少个符号

样例输入:
    print("I don't know!");
    // 123456789
    end
样例输出:
    字母: 14
    数字: 9
    符号: 12
    一共:35
    (end表示结束, 所以不计入)

代码

public class Homework0611 {
    public static void main(String[] args) {
        String str = print();       //用户输入

        int[] count = method(str);  //计数
        System.out.println("\n******结果******");
        System.out.println("字母: " + count[0]);
        System.out.println("数字: " + count[1]);
        System.out.println("符号: " + count[2]);
    }

    /**
     * 用户输入
     * @return 输入的字符串
     */
    public static String print() {
        Scanner sc = null;
        String str = null;  //字符串
        String temp = null; //临时变量
        System.out.println("******请输入本程序代码******");
        while(true){
            sc = new Scanner(System.in);
            temp = sc.nextLine();
            str += temp;    //字符串拼接
            if ("end".equals(temp)){    //遇到end 结束输入
                str = str.substring( 4, str.length() - 3 ); //去掉null,end
                return str;
            }
        }
    }

    /**
     * 计数方法
     * @param str   输入的字符串
     * @return  计数结果
     */
    public static int[] method(String str) {
        int countL = 0; //计数字母
        int countN = 0; //计数数字
        int countS = 0; //计数符号
        char c = 0; //存放字符

        for (int i = 0; i < str.length(); i++){ //遍历
            c = str.charAt(i);
            if (48 <= c && c <= 57){    //阿拉伯数字:48~57
                countN++;
            }else if(65 <= c && c <= 90 || 97 <= c && c <= 122){    //大写英文字母:65~90;小写英文字母:97~122
                countL++;
            }else{
                countS++;   //是符号
            }
        }
        int[] count = {countL, countN, countS}; //数组存放 字母,数字,符号 的计数结果
        return count;
    }
    
}

运行结果

******请输入本程序代码******
print("I don't know!");
// 123456789
end

******结果******
字母: 14
数字: 9
符号: 12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值