题目描述
输入一行字符,以回车符作为输入结束的标志。统计其中英文字母、数字字符和其他字符的个数。
输入
多个字符,以回车符结束,回车符不作为有效字符。有效字符个数不超过100。
输出
输出分3行,格式见输出样例。
样例输入 Copy
Abse 4+5*3=?
样例输出 Copy
letter:4
digit:3
other:5
结题思路:
在进行结题时,我先是想用0<=ch<=9;a<=ch<=z等这种判断,想着是不是有点太low了。然后就上网搜了一下java有没有封装好的代码,后来一查果然有,判断数字和字符的都有写好的方法,我们只要拿来用就好了。这里我先输入一串字符串,然后把字符串转换为字符数组,再用for循环进行遍历,遍历的同时,用If语句进行判断,然后针对数字、字符、其他字符都设置了一个计数器,每当判断后,如果符合,就加1。
实现代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char[] ch = str.toCharArray();
int count = 0; //统计数字
int count1 = 0; //统计字母
int count2 = 0; //统计其他字符
for (int i = 0; i < ch.length; i++) {
if (Character.isDigit(ch[i])) {
count++;
}else if (Character.isLetter(ch[i])) {
count1++;
}else {
count2++;
}
}
System.out.println("letter:"+count1);
System.out.println("digit:"+count);
System.out.println("other:"+count2);
}
}