题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。程序分析:利用while语句,条件为输入的字符不为'\n'.
1 回答
yanrun
TA贡献317条经验 获得超240个赞
public class Test{
public static void main(String[] args) {
String str = "adasf AAADFD我是中文,,》123";
count(str);
}
private static void count(String str) {
char[] chars = str.toCharArray();
int i = 0;
int numCount = 0;
int spaceCount = 0;
int letterCount = 0;
int otherCount = 0;
while(i < chars.length) {
if((chars[i] >= 'a' && chars[i] <= 'z') || (chars[i] >= 'A' && chars[i] <= 'Z')) {
letterCount++;
} else if(chars[i] >= '0' && chars[i] <= '9') {
numCount++;
} else if(chars[i] == ' ') {
spaceCount++;
} else {
otherCount++;
}
i++;
}
System.out.println("数字共有:" + numCount + "个");
System.out.println("字母共有:" + letterCount + "个");
System.out.println("空格共有:" + spaceCount + "个");
System.out.println("其他字符共有:" + otherCount + "个");
}
}添加回答
举报
0/150
提交
取消
