java50题----07统计字符数

来源:互联网 发布:mac怎么导入iphone照片 编辑:程序博客网 时间:2024/06/06 18:45
/*输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。*/import java.io.*;import java.lang.Character.*;class Demo{private Demo(){}private static Demo instance = new Demo();private int alfabetCount = 0;private int spaceCount = 0;private int numCount = 0;private int otherCount = 0;public static Demo getInstance(){return instance;}private void parse(String str){char[] arr;arr = str.toCharArray();setZero();for(int i=0; i<arr.length; i++){if(arr[i] >='0' && arr[i]<= '9')numCount++;else if((arr[i]>='a' && arr[i]<='z') || (arr[i]>='A' && arr[i]<='Z'))alfabetCount++;else if(arr[i]=='\t' || arr[i]=='\n' || arr[i]=='\f'||arr[i]=='\r' || arr[i] == ' ')spaceCount++;elseotherCount++;}}private void setZero(){alfabetCount = 0;spaceCount = 0;numCount = 0;otherCount = 0;}public void getCounts(String str){parse(str);printFunction("alfabetCount:\t"+alfabetCount);printFunction("numCount:\t"+numCount);printFunction("spaceCount:\t"+spaceCount);printFunction("otherCount:\t"+otherCount);}private void printFunction(Object obj){System.out.println(obj.toString());}}class MainClass {public static void main(String[] args)throws Exception {Demo d = Demo.getInstance();System.out.println("Please Input a string:");////录取键盘输入字节流对象InputStream in = System.in;//////将字节流对象转换成字符流对象InputStreamReader reader = new InputStreamReader(in);//////使用缓冲技术读取字符流对象BufferedReader buf = new BufferedReader(reader);String str = "";while(true){str = buf.readLine();if(str.isEmpty() != true){if(str.equals("quit")==true){System.exit(0);}d.getCounts(str);}}}}/*判断字符真是费劲。。。看着就别扭。电子书中的代码好像有问题,ch是数组这么判断编译时提示错误。   ch= s.toCharArray();     for(inti=0; i<ch.length; i++) {      if(ch>= '0' &&ch<= '9') {      digital ++;      }else if((ch>= 'a' &&ch<= 'z') || ch > 'A' &&ch <= 'Z'){      character++;      }else if(ch== ' '){      blank++;      }else {      other++;      }      } */


                                             
0 0
原创粉丝点击