利用Java语言代码输入一行字符分别统计其中英文字母、空格、数字和其他字符的个数。

Python048

利用Java语言代码输入一行字符分别统计其中英文字母、空格、数字和其他字符的个数。,第1张

123456789101112131415161718192021222324public static void main(String[] args) throws IOException {        BufferedReader br=new BufferedReader(new InputStreamReader(System.in))        String str=br.readLine()         int countNum = 0//统计数字的个数        int countChar = 0//统计英文字母的个数        int countSpace = 0//统计空格的个数        int countOthers = 0//统计其它字符的个数        for (int i = 0 i < str.length() i++) {            char c = str.charAt(i)            if (c >= '0' && (int) c <= '9') {                countNum++            } else if ((c >= 'a' && c <= 'z')||(c >= 'A' && c <= 'Z')) {                countChar++            } else if (c == ' ') {                countSpace++            } else{                countOthers++            }        }        System.out.println("数字个数:"+countNum)        System.out.println("英文字母个数:"+countChar)        System.out.println("空格个数:"+countSpace)        System.out.println("其他字符个数:"+countOthers)    }

一、问题分析:

输入一行字母,那么会以换行结束。所以可以存入数组,也可以逐个输入,遇到换行结束。

要统计各个类的个数,就要逐个判断是哪个分类的。

由于在ASCII码中,数字,大写字母,小写字母分别连续,所以可以根据边界值判断类型。

二、算法设计:

1、读入字符,直到遇到换行结束。

2、对于每个字符,判断是字母还是数字,或者空格,或者是其它字符。

3、对于每个字符判断后,对应类别计数器自加。

4、最终输出结果。

import java.util.Scanner

/**

 * 统计字符串中数字,字母,空格,其他字符的个数

 * @author Administrator

 *

 */

public class Data01 {

public static void main(String[] args) {

int englishCount = 0// 英文字母个数

int spaceCount = 0// 空格个数

int numCount = 0// 数字个数

int otherCount = 0// 其他字符个数

Scanner sc = new Scanner(System.in)

System.out.println("请您输入一行字符:")

String str = sc.nextLine()// 取得控制台输入的一行字符

char[] ch = str.toCharArray()// 把取道的字符串变成一个char数组

for (int i = 0 i < ch.length i++) {

if (Character.isLetter(ch[i])) {

// 判断是否为字母

englishCount++

} else if (Character.isSpaceChar(ch[i])) {

// 判断是否为空格

spaceCount++

} else if (Character.isDigit(ch[i])) {

// 判断是否为数字

numCount++

} else {

// 以上都不是则认为是其他字符

otherCount++

}

}

System.out.println("字母的个数:" + englishCount)

System.out.println("数字的个数:" + numCount)

System.out.println("空格的个数:" + spaceCount)

System.out.println("其他字符的个数:" + otherCount)

}

}