0
点赞
收藏
分享

微信扫一扫

JAVA实现在键盘上输入一串字符,判断输入各类型字符的数量

古得曼_63b6 2022-03-24 阅读 46
eclipse

内容:在键盘上随意输入一段字符,字符可能会是数字,英文大小写字母,标点,空格等等不同类型,然后写一段程序实现对不同类型字符数量的计数。

平台:JAVA eclipse

首先,先定义一下几个变量的数据类型

public class test001 {
     public static void main(String[] args) {
    	 int ch=0;
    	 int numb=0;
    	 int spac=0;
    	 int other=0;

然后,用Scanner实现从键盘获取一串字符。

System.out.println("请输入一串字符。");
    	 String enterNum;
    	 Scanner sc=new Scanner(System.in);
    	 enterNum=sc.nextLine();

然后得出字符的长度。

enterNum.length();

接下来使用for循环,以实现从字符串第一个字符到最后一个字符的遍历。

charAt()方法可得到字符串某个位置的字符是什么。

而后用if,else if语句实现对字符类型的判断。

 for (int i=0;i<=enterNum.length()-1;i++) {
    			 char result=enterNum.charAt(i);
    			 if ('A'<=result&&result<='Z'||'a'<=result&&result<='z') {
    				 ch++;
    			 }else if ('0'<=result&&result<='9') {
    				 numb++;
    			 }else if (result==' ') {
    				 spac++;
    			 }else {other++;}
    		 }

最后输出结果就可以了。

 System.out.println("英文字母个数为"+ch);
    		 System.out.println("数字的个数为"+numb);
    		 System.out.println("空格的个数为"+spac);
    		 System.out.println("其他字符的个数为"+other);
     }
}

本人是新手,对java理解不深,对代码的解释虽说尽我所能,但仍有不足之处,欢迎指正补充。

举报

相关推荐

0 条评论