代码原创,可借鉴。
问题描述:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。并打印出来。
package Demo;
import java.util.Locale;
import java.util.Scanner;
public class Demo16 {
public static void main(String[] args) {
//输入的是一行字符串,分别统计英文字母,空格,数字,和其他字符共4种。
Scanner in = new Scanner(System.in);
System.out.println("Please input a sentence:");
String str = in.nextLine().toLowerCase(Locale.ROOT);//统一字母的大小写
char[] ch = new char[str.length()];
for (int i = 0; i < ch.length; i++) {
ch[i] = str.charAt(i);//转换为数组好比较
}
nums(ch);//调用函数
in.close();
}
public static void nums(char[] ch){
int[] a = new int[4];//定义四个数组用来存储4种符号
for (int i = 0; i < ch.length; i++) {
if (ch[i]>='0'&&ch[i]<='9'){
a[0]++;
}else if (ch[i]>='a'&&ch[i]<='z'){
a[1]++;
}else if (ch[i]==' '){
a[2]++;
}else {
a[3]++;
}
}
System.out.println("The number of numbers is: "+a[0]);
System.out.println("The number of English letters is: "+a[1]);
System.out.println("The number of blank space is: "+a[2]);
System.out.println("The number of other characters is: "+a[3]);
}
}