欢迎您访问新疆栾骏商贸有限公司,公司主营电子五金轴承产品批发业务!
全国咨询热线: 400-8878-609

新闻资讯

常见问题

java判断各类型字符个数实例代码

作者:用户投稿2026-01-11 05:49:33
目录
  • 描述
  • 输入描述:
  • 输出描述:

描述

输入一行字符串,分别统计出其中英文字母、空格、数字和其它字符的个数

输入描述:

控制台随机输入一串字符串

输出描述:

输出字符串中包含的英文字母个数,数字个数,空格个数,其它字符个数(格式为:英文字母x数字x空格x其他x),预设代码中已给出输出.

import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        int numbers = 0;
        int words = 0;
        int space = 0;
        int other = 0;
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
 
        //write your code here......
        
 
        System.out.println("英文字母"+words+"数字"+numbers+"空格"+space+"其他"+other);
    }
}
import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        int numbers = 0;
        int words = 0;
        int space = 0;
        int other = 0;
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
 
        //write your code here......
        for(int i=0;i<str.length();i++){
            char c=str.charAt(i);
            if((c>='a' && c<='z')|| (c>='A' && c<='Z')){
                words++;
                continue;
            }
            if(c>='0' && c<='9' ){
                numbers++;
                continue;
            }
            if(c==' '){
                space++;
                continue;
            }
            else{
                other++;
                continue;
            }
        }
 
        System.out.println("英文字母"+words+"数字"+numbers+"空格"+space+"其他"+other);
    }
}
 
 

注意:每次计数完后要跳出循环,否则就取出的字符会挨个问一遍判断语句 出现问题