java基础练习

package cn.leaveriver.practice;
import java.util.Scanner;
/**
 * 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
 * ascII码值:数字0-9是48-57,字母是65-90和97-122,空格是32
 */
public class Demo01 {
    public static void main(String[] args) {
        int num = 0;
        int letterNum = 0;
        int spaceNum = 0;
        int other = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一段字符:");
        String s = scanner.nextLine(); //读一行
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c >= '0' && c <= '9'){ //0-9也可以用  48<c<57
                num++;
            }else if ((c >= 65 && c <= 90) || (c >= 97 && c < 122)){//A-Z 或者a-z
                letterNum++;
            }else if (c == 32){// 空格
                spaceNum++;
            }else {  //其他
                other++;
            }
        }
        System.out.println("其中数字有" + num + "个,字母有"+letterNum+"个,空格有"+spaceNum+"个,其他有"+other+"个。");
    }
}

版权声明:本文为qq_42852943原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。