题目:键盘输入一个字符串,并且统计各种字符出现的个数(种类有:大写字母,小写字母,数字,其他字符)
解题思路:
1. 键盘输入,要用到Scanner类
2. 输入的是字符串,就要用到对象.next();
3. 对种类进行统计,要分门别类,则要四个变量;
4. 要遍历字符串中每个字符,因此要把String-》char[]
5. 转变可以用方法:toCharArray():
6. for里面进行if判断
String str = scn.next();//确定输入的是字符串
char[] array = str.toCharArray();//将字符串拆分成字符数组
判断和统计在方法里面进行;;;
下面是完整代码:
package cn.itcast.day0607.demo04;
import java.util.Scanner;
/*
从键盘输入一串字符串,并且统计其中数字字符,大写字符,小写字符,其他字符
思路:
键盘输入要用到Scanner
要用到字符串,要拆分成字符数组用到toCharArray
*/
public class Demo01SumWord {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("请输入一段字符串:");
String str = scn.next();//确定输入的是字符串
char[] array = str.toCharArray();//将字符串拆分成字符数组
sumWord(array);
}
public static void sumWord(char[] array) {
int countNumber = 0;
int countBigWord = 0;
int countSmallWord = 0;
int countOthers = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] >= '0' && array[i] <= '9')
countNumber++;
else if (array[i] >= 'a' && array[i] <= 'z') {
countSmallWord++;
} else if (array[i] >= 'A' && array[i] <= 'Z') {
countBigWord++;
} else {
countOthers++;
}
}
System.out.println("数字有:" + countNumber);
System.out.println("大写字母有:" + countBigWord);
System.out.println("小写字母有:" + countSmallWord);
System.out.println("其他字符有:" + countOthers);
}
}
运行结果例如:

谢谢你的检阅,小白很是感动~~~
本文介绍了一种使用Java编程语言统计字符串中不同字符类型(包括数字、大写字母、小写字母和其他字符)的方法。通过将字符串转换为字符数组并遍历每个字符,利用条件判断实现了对每种字符类型的计数。
&spm=1001.2101.3001.5002&articleId=106597107&d=1&t=3&u=040c4ad7672a410d9efc44f736bc60b6)
8774

被折叠的 条评论
为什么被折叠?



