用JAVA输人一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
时间: 2023-11-23 14:04:02 浏览: 37
好的,以下是JAVA代码示例:
```
import java.util.Scanner;
public class CharacterCount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一行字符:");
String str = input.nextLine();
int letterCount = 0;
int spaceCount = 0;
int digitCount = 0;
int otherCount = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
letterCount++;
} else if (Character.isDigit(ch)) {
digitCount++;
} else if (Character.isSpaceChar(ch)) {
spaceCount++;
} else {
otherCount++;
}
}
System.out.println("统计结果如下:");
System.out.println("英文字母个数:" + letterCount);
System.out.println("空格个数:" + spaceCount);
System.out.println("数字个数:" + digitCount);
System.out.println("其他字符个数:" + otherCount);
}
}
```
以上代码中,我们使用 for 循环遍历输入的字符串,通过判断每个字符的类型进行字符统计。其中,`Character.isLetter()`、`Character.isDigit()`、`Character.isSpaceChar()` 三个方法可以判断字母、数字、空格字符类型,其余则为其他字符类型。最终输出各类型字符的个数。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)