输入任意长的一个字符串,统计其字母、数字、空格及其他字符的数量。

  思路:简单的利用一个多重 if 结构就可以解决。

 

  CODE:

import java.util.Scanner;

public class Character{
  public static void main(String[] args){
    System.out.println ("请输入一个字符串:");
    Scanner ss = new Scanner(System.in);
    String sc = ss.nextLine();
    char[] ch= sc.toCharArray(); //字符串变成字符数组
    int abccount = 0;
    int numcount = 0;
    int spacecount = 0;
    int othercount = 0;
    for (int i = 0;i<sc.length();i++){
      if(ch[i]<='9'&&ch[i]>='0'){
        numcount++;
      }else if((ch[i]<='z'&&ch[i]>='a')||(ch[i]<='Z'&&ch[i]>='A')){
        abccount++;
      }else if(ch[i]==' '){
        spacecount++;
      }else{
        othercount++;
      }
    }
    System.out.println ("数字的个数为:"+numcount);
    System.out.println ("字母的个数为:"+abccount);
    System.out.println ("空格的个数为:"+spacecount);
    System.out.println ("其他字符个数为:"+othercount);
  }
}

posted @ 2015-12-03 22:02  Mz丶  阅读(5920)  评论(0编辑  收藏  举报