练习7

来源:互联网 发布:lda模型 矩阵分解 编辑:程序博客网 时间:2024/05/22 17:41

题目:输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数。

分析:先将输入的字符串利用toCharArray()转化为字符数组,然后统计字符数组中的元素分别为英文字母,空格,数字和其他字符的个数。

代码:
import java.util.*;public class Practice7 {public static void main(String[] args){Scanner str = new Scanner(System.in);System.out.println("请输入一串字符:");//例如输入:asdf132 faASD,/.,  12 FA . dasf 12r4..>/'asdkf ;asd fl;jo3029 ru032 9r4String s = str.nextLine();  //定义输入的一行字符int l = 0;  //定义英文字母个数lint b = 0;  //定义空格个数bint n = 0;  //定义数字个数nint o = 0;  //定义其他字符个数ochar[] ch = null;  //定义输入字符数组ch = s.toCharArray();  //将字符串s转化为字符数组chfor(int i = 0; i < ch.length; i++){  //判断每个字符是什么类型的if(((ch[i] >= 'a') && (ch[i] <= 'z')) || ((ch[i] >= 'A') && (ch[i] <= 'Z'))){l++;  //若字符为字母则l加1}else if(ch[i] == ' '){b++;  //若字符为空格则b加1}else if((ch[i] >= '0') && (ch[i] <= '9')){n++;  //若字符为数字则n加1}else{o++;  //字符为其他类型则o加1}}System.out.println("字符串中英文字母的个数为:" + l);System.out.println("字符串中空格的个数为:" + b);System.out.println("字符串中数字的个数为:" + n);System.out.println("字符串中其他字符的个数为:" + o);  //输入各种类型字符的个数str.close();}}
结果:


原创粉丝点击