The number of statistical exercises string string of uppercase, lowercase, numbers 29

String traversal exercises

demand analysis

Keyboard input a string, count the number of characters in the string uppercase letters, lowercase alphabetic characters, numeric characters appear (without regard to other characters)

Analysis step

1, a keyboard input string.
2, the counter variable is defined: record the number of uppercase / lowercase / numeric characters appear
3, traverse the string
4, to obtain the current character, judgment is uppercase, lowercase, or digital. Sequentially accumulating its counter
5, after the loop counter variable output current to three

import java.util.Scanner;

public class StringExecDemo03 {
    public static void main(String[] args) {
        //1、键盘录入一个字符串。
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一个字符串:");
        String data = sc.nextLine();

        //2、定义计数器变量:记录大写/小写/数字字符出现的次数
        int upperCount = 0;
        int lowerCount = 0;
        int numberCount = 0;

        //3、遍历字符串
        for (int i = 0; i < data.length(); i++) {
            char ch = data.charAt(i);
            //4、得到当前字符,判断是大写,小写,还是数字。依次累加其计数器
            if (ch >= 'a' && ch <= 'z') {
                lowerCount++;
            } else if (ch >= 'A' && ch <= 'Z') {
                upperCount++;
            } else if (ch >= '0' && ch <= '9') {
                numberCount++;
            }
        }

        System.out.println("大写出现次数" + upperCount + "小写出现次数" + lowerCount + "数字出现的次数" + numberCount);

    }
}

Published 34 original articles · won praise 16 · views 275

Guess you like

Origin blog.csdn.net/qq_41005604/article/details/105272891