键盘录入一个字符串,统计该字符串中的大写字母、小写字母、数字字符和其他字符分别有多少个
例如,键盘录入abcABCD12345!@#$%&,输出结果为:小写字母有3个,大写字母有4个,数字字符有5个,其他字符有6个
代码:
import java.util.Scanner;
public class Demo08 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入任意字符,将返回字符个数:");
String str = sc.nextLine();
chStatistical(str);
}
/*
* 统计键盘输入的字符串中的大写字母、小写字母、
* 数字字符和其他字符分别有多少个
*/
public static void chStatistical(String str) {
char[] ch = str.toCharArray();
int upperCount = 0;
int lowerCount = 0;
int numCount = 0;
int otherCount = 0;
for (int i = 0; i < ch.length; i++) {
if(ch[i] >= 65 && ch[i] <= 90) {
upperCount++;
}else if(ch[i] >= 97 && ch[i] <= 122) {
lowerCount++;
}else if(ch[i] >= 48 && ch[i] <= 57) {
numCount++;
}else {
otherCount++;
}
}
System.out.println("大写字母有:"+upperCount+"个");
System.out.println("小写字母有:"+lowerCount+"个");
System.out.println("数字有:"+numCount+"个");
System.out.println("其他字符有:"+otherCount+"个");
}
}