2019/3/30/ 20:48
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
package test;
import java.util.*;
public class ZiMu {
public static Scanner input = new Scanner(System.in);//获取键盘输入的数
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入一行字符串:");//提示输入字符串
String str = input.nextLine();
int a = 0,b = 0, c = 0, d = 0;//定义四个变量分别为abcd 用来存储字母,数字,空格和其他字符的个数
char [] ch = str.toCharArray();//String的方法,将字符串转换为字符数组;
for (int i = 0; i <ch.length; i++) {//for 循环查找数组的值
if(ch[i] >= 'a' && ch[i] <= 'z' || ch[i] >= 'A' && ch[i] <= 'Z')//从数组ch下标0开始匹配,当为字母时a自增一次
a++;
else if(ch[i] >= '0' && ch[i] <= '9')//当为数字时b自增一次
b++;
else if(ch[i] == ' ')//当为空格时c自增一次
c++;
else//其他数值d自增一次
d++;
}
System.out.println("字母个数:"+a);
System.out.println("数字个数:"+b);
System.out.println("空格个数:"+c);
System.out.println("其他个数:"+d);
}
}
