java练习的小记录
加强对字符串基本操作的理解 不足之处还望多多指正
import java.util.Scanner;
/*
* 键盘 输入的字符串 统计各种字符出现的次数
* 大写字母 小写字母 数字 其他
* Scanner 接收字符串
* 定义四个变量 分别代表四种字符各自的出现次数
* 对每一个字符串进行检查 使用toCharArray()方法
* 遍历char[]字符数组 对当前字符的种类进行判断
*/
public class StringConutDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一串字符串: ");
String next = sc.next();
int countUpper = 0; // 大写字母
int countLoper = 0; // 小写字母
int countNumber = 0; // 数字
int countOther = 0; // 其他字符
char[] charArray = next.toCharArray();// 把接收的字符返回char类型数组 就要用到toCharArray方法
for( int i = 0; i < charArray.length; i++ ) {
char ch = charArray[i]; // 表示当前单个字符
if ( 'A' <= ch && ch<= 'Z') {
countUpper++;
} else if ( 'a' <= ch && ch <= 'z') {
countLoper++;
} else if ( '0' <= ch && ch <= '9') {
countNumber++;
} else {
countOther++;
}
}
System.out.println("大写字母有: " + countUpper);
System.out.println("小写字母有: " + countLoper);
System.out.println("数字有: " + countNumber);
System.out.println("其他字符有: " + countOther);
}
}