09练习:统计输入的字符串中各种字符的个数


 1 package com.Commonly.Practise;
 2 
 3 import java.util.Scanner;
 4 
 5 /*
 6 题目:
 7 键盘输入一个字符串,并且统计其中各种字符出现的次数。
 8 种类有:大写字母、小写字母、数字、其他
 9 
10 思路:
11 1.既然用到键盘输入,肯定是Scanner
12 2.键盘输入的是字符串,那么:String str = sc.next();
13 3.定义四个变量,分别代表四种字符各自出现的次数。
14 4.需要对字符串一个字、一个字检查,String-->char[],方法就是toCharArray()
15 5.遍历char[]字符数组,对当前字符的种类进行判断,并且用四个变量进行++动作
16 6.打印输出四个变量,分别代表四种字符出现次数。
17  */
18 public class month16practise02 {
19     public static void main(String[] args) {
20         Scanner sc = new Scanner(System.in);
21         System.out.println("请输入一个字符串:");
22         String input = sc.next();//获取键盘输入的一个字符串
23 
24         int countUpper = 0;//大写字母
25         int countLower = 0;//小写字母
26         int countNumber = 0;//数字
27         int countOther = 0;//其他字符
28 
29         char[] charArray = input.toCharArray();
30         for (int i = 0; i < charArray.length; i++) {
31             char ch = charArray[i];//当前单个字符
32             if ('A'<=ch&&ch<='Z'){
33                 countUpper++;
34             }else if ('a'<=ch&&ch<='z'){
35                 countLower++;
36             }else if ('0'<=ch&&ch<='9'){
37                 countNumber++;
38             }else {
39                 countOther++;
40             }
41         }
42         System.out.println("大写字母有:"+countUpper);
43         System.out.println("小写字母有:"+countLower);
44         System.out.println("数字有:"+countNumber);
45         System.out.println("其他字符有:"+countOther);
46     }
47 }

相关