【程序7】
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
public class lx07 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一行字符串:");
String str = sc.nextLine();//next读取到空格就结束了,nextline读取到回车结束,所以字符串里有空格用nextline
char[] chars = null;
chars = str.toCharArray();//将字符串转变为字符数组
int zimu = 0 , digital = 0 , blank = 0 , other = 0 ;
for (int i = 0; i < chars.length; i++) {
if (chars[i] >= 'a' && chars[i] <= 'z' || chars[i] >= 'A' && chars[i] <= 'Z'){
zimu++;
}else if (chars[i] >= '0' && chars[i] <= '9'){
digital++;
}else if (chars[i] == ' '){
blank++ ;
}else {
other++;
}
}
System.out.println("字母个数:" + zimu);
System.out.println("数字个数:" + digital);
System.out.println("空白个数:" + blank);
System.out.println("其它个数:" + other);
}
}