用java编写一个程序,统计输入的一串字符内,大小写字母,数字,空格以及其他字符的个数
时间: 2024-09-25 07:02:16 浏览: 78
在Java中,我们可以创建一个简单的程序来统计字符串中各种字符类型的数量。下面是一个基本示例:
```java
import java.util.Scanner;
public class CharacterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一串字符:");
String input = scanner.nextLine();
int uppercaseCount = 0;
int lowercaseCount = 0;
int digitCount = 0;
int spaceCount = 0;
int otherCharactersCount = 0;
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i);
if (Character.isUpperCase(currentChar)) {
uppercaseCount++;
} else if (Character.isLowerCase(currentChar)) {
lowercaseCount++;
} else if (Character.isdigit(currentChar)) {
digitCount++;
} else if (currentChar == ' ') {
spaceCount++;
} else {
// 其他非字母、数字和空格的字符
otherCharactersCount++;
}
}
System.out.println("大写字母数量: " + uppercaseCount);
System.out.println("小写字母数量: " + lowercaseCount);
System.out.println("数字数量: " + digitCount);
System.out.println("空格数量: " + spaceCount);
System.out.println("其他字符数量: " + otherCharactersCount);
}
}
```
这个程序首先获取用户输入,然后遍历每个字符,通过`Character`类提供的静态方法如`isUpperCase()`、`isLowerCase()`和`isdigit()`来判断字符的类型,并计数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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)