本帖最后由 唯伟123 于 2014-4-30 22:45 编辑
:victory::victory::victory::victory::victory::victory::victory::victory::victory::victory::victory::victory::victory::victory::victory::victory:
- package cn.itheima_01;
- import java.util.Scanner;
- /*
- * 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
- *
- */
- public class CountTest {
- public static void main(String[] args) {
- // 封装键盘录入
- Scanner sc = new Scanner(System.in);
- // 键盘输入数据
- System.out.println("请输入一行字符:");
- String s = sc.nextLine();
-
- //将字符串转换为字符数组
- char[] chs = s.toCharArray();
- //定义统计量
- int lettleCount = 0;//字母个数
- int spaceCount = 0;//空格个数
- int numberCount = 0;//数字个数
- int otherCount = 0;//其他字符个数
- //使用for循环遍历匹配
- for (int x=0; x<chs.length; x++){
- if((chs[x]>='a'&&chs[x]<='z')||(chs[x]>='A'&&chs[x]<='Z'))
- lettleCount++;
- else if (chs[x] == ' ')
- spaceCount++;
- else if (chs[x]>='0'&&chs[x]<='9')
- numberCount++;
- else
- otherCount++;
- }
- System.out.println("字母个数为: "+lettleCount);
- System.out.println("空格个数为: "+spaceCount);
- System.out.println("数字个数为: "+numberCount);
- System.out.println("其他字符个数为: "+otherCount);
-
-
- }
- }
复制代码
|