首页 > 代码库 > 7 判断输入字符个数

7 判断输入字符个数

 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

 1           public class _007CountStringAll {
 2 
 3     public static void main(String[] args) {
 4         printCount();
 5     }
 6 
 7     private static void printCount() {
 8         while (true) {
 9             Scanner scanner = new Scanner(System.in);
10             System.out.println("请输入一组字符 : ");
11             String string = scanner.nextLine();
12             char[] ch = string.toCharArray();
13             count(ch);
14         }
15     }
16 
17     private static void count(char[] ch) {
18         int adbCount = 0;
19         int spaceCount = 0;
20         int numCount = 0;
21         int otherCount = 0;
22 
23         for (int i = 0; i < ch.length; i++) {
24             // 判断是否是字母
25             if (Character.isLetter(ch[i])) {
26                 adbCount++;
27             } //判断是否是数字
28             else if (Character.isDigit(ch[i])) {
29                 numCount++;
30             } else if (Character.isSpaceChar(ch[i])) {
31                 spaceCount++;
32             } else {
33                 otherCount++;
34             }
35         }
36         System.out.println("字母个数是:" + adbCount);
37         System.out.println("数字个数是:" + spaceCount);
38         System.out.println("空格个数是:" + numCount);
39         System.out.println("其他字符个数是:" + otherCount);
40     }
41 
42 }

 

7 判断输入字符个数