**每天一道JavaSE基础题(七、字符内容判断与统计:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。)**
【程序7】
- 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
- 分析:先判断字符类型,然后累加
程序代码:
package SE50T;
import java.util.Scanner;
/*
* 【程序7】
* 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
*
*/
public class T7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int english = 0,space = 0,shuzi = 0,others = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (Character.isDigit(c[i])) {
shuzi++;
}else if (Character.isLetter(c[i])) {
english++;
}else if (Character.isSpaceChar(c[i])) {
space++;
}else {
others++;
}
}
System.out.println("英语字母有:" + english + "个");
System.out.println("空格有:" + space + "个");
System.out.println("数字有:" + shuzi + "个");
System.out.println("其他字符有:" + others + "个");
}
}
程序运行图: