Java basic arithmetic questions (07): Enter a line of characters, respectively, the statistics of the number of letters, spaces, numbers and other characters in them.

View all 50 basic arithmetic questions, see:

Java basic algorithm of 50 questions

package Demo07Character_Count;
import java.util.Scanner;
public class Caracter_Count {
    /**
     * 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
     */
    /*
    分析:这道题没有说要统计每个字符的个数,而只是统计英文字母,空格,数字和其它字符的个数,所以,我们用简单的
          变量来计数就可以了。可以考虑把用户输入的字符串toCharArray()一下,再一一对比判断。
     */
    public static void main(String[] args) {
            System.out.println("请输入一段字符串……");
            Scanner sc = new Scanner(System.in);
            // 获取用户输入的字符串,因为Scanner类的next()方法遇到空格或enter会终止,所以这里用nextLine()方法获取整行
            String str = sc.nextLine();
            System.out.println(str);
            // 分解
            char[] chars = str.toCharArray();
            // 定义四个变量来计数
            int letters = 0;
            int numbers = 0;
            int spaces = 0;
            int others = 0;
            // 遍历数组并计数
            for (int i = 0; i < chars.length; i++) {
                if ((chars[i] >= 'A') && (chars[i]) <= 'Z') {
                    letters++;
                } else if ((chars[i] >= 'a') && (chars[i]) <= 'z') {
                    letters++;
                } else if ((chars[i] >= '0') && (chars[i]) <= '9') {
                    numbers++;
                } else if (chars[i] == ' ') {
                    spaces++;
                } else {
                    others++;
                }
            }
            System.out.println("您刚输入的字符串中英文字符有:" + letters + "个。");
            System.out.println("数字字符有:" + numbers + "个。");
            System.out.println("空格字符有:" + spaces + "个。");
            System.out.println("其它字符有:" + others + "个。");
    }
}
Published 22 original articles · won praise 1 · views 1425

Guess you like

Origin blog.csdn.net/weixin_44803446/article/details/105354760
Recommended