统计字符的个数

package com.itheima_07;

import java.util.Scanner;

/*
 * 统计字符的个数:
 * 	题目:输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数.
 * 
 * 需求分析:
 * 		英文字母:'a'~'z'或'A'~'Z'
 * 		空格:' '
 *		数字:0~9
 *		其它字符:other 		
 */

public class StatisticsNumber {
	//主方法
	public static void main(String[] args) {
		//键盘录入两个数,static InputStream in,被static修饰的字段,可以使用类名System直接调用
		Scanner sc = new Scanner(System.in);
		//输入提示语,System:static PrintStream out,PrintStream:void println(String x)
		System.out.println("请输入一行字符:");
		//接收字符串,Scanner:String nextLine()  
		String str = sc.nextLine();
		//定义统计变量
		int count1 = 0;
		int count2 = 0;
		int count3 = 0;
		int count4 = 0;
		//遍历字符串,for循环
		for (int i = 0; i < str.length(); i++) {
			//接收一个字符,String:char charAt(int index)
			//使用while循环判断是否有回车
			//统计英文字母
			if (str.charAt(i)>='a'&&str.charAt(i)<='z'||str.charAt(i)>='A'&&str.charAt(i)<='Z') {
				count1++;
			//统计空格
			}else if (str.charAt(i)==' ') {
				count2++;
			//统计数字
			} else if (str.charAt(i)>='0'&&str.charAt(i)<='9') {
				count3++;
			//统计其它字符的个数
			} else {
				count4++;
			}
		}
		//输出,分别统计出其中英文字母,空格,数字和其他字符的个数
		System.out.println("英文字母的个数为:"+count1+"  空格的个数为:"+count2+"  数字的个数为:"+count3+"  其它的字符的个数为:"+count4);
	}
}

猜你喜欢

转载自blog.csdn.net/guan_moyi/article/details/80044061