黑马程序员技术交流社区

标题: java基础-字符串和if-else的使用 [打印本页]

作者: bl141421    时间: 2015-7-10 21:50
标题: java基础-字符串和if-else的使用

/*
需求:键盘输入一个字符串  统计其中的数字、英文字母、空格符号和其他符号的个数。

思路:1.先用四个变量分别记录要统计的字符
      2.把字符串转化成字符数组,然后遍历
          3.判断数组中的每一个字符,并记录数量
          4.输出数量

*/
import java.util.Scanner;

public class Test5
{
        public static void main(String [] args)
        {
       
                //1.先用四个变量分别记录要统计的字符
                int integer =0;
                int english =0;
                int space = 0;
                int other = 0;

                char [] ch =null ;

                Scanner sc =new Scanner(System.in);

                String s =sc.nextLine();

                ch = s.toCharArray();
               
                 //2.把字符串转化成字符数组,然后遍历
                for (int x =0;x<ch.length;x++ )
                {
                        //3.判断数组中的每一个字符,并记录数量
                        if(ch[x]>='0'&&ch[x]<='9'){
                                integer++;
                        }
                        else if(ch[x]>='a'&&ch[x]<='z'||ch[x]>='A'&&ch[x]<='Z'){
                                english++;
                        }
                        else if(ch[x]==' '){
                                space++;
                        }
                        else {
                                other++;
                        }
                }
                         //4.输出数量
                System.out.println("数字"+integer+"个,英文字母"+english+"个,空格"+space+"个,其他"+other+"个");
       

       
        }
}







作者: 张亚昆    时间: 2015-7-10 22:03
学到了。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2