[Java] 纯文本查看 复制代码
package com.heima.test;
import java.util.Scanner;
public class Test07{
/*
*题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
1.程序分析:利用while语句,条件为输入的字符不为'\n'.
*/
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("输入一行字符");
String str = sc.nextLine();
count(str);
}
//统计输入的字符数
private static void count(String str) {
//计数器
int countLetter = 0;
int countSpace = 0;
int countNumber =0;
int countOther = 0;
//将字符串转成字符数组存储
char[] ch = str.toCharArray();
/* for (int j = 0; j < ch.length; j++) {
if (ch=='\n') {
break;
}else if (ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') {
countLetter++;
}else if (ch>='0'&&ch<='9') {
countNumber++;
}else if (ch==' ') {
countSpace++;
}else {
countOther++;
}
i++;
}*/
int i = 0;
while (ch!='\n') { //i<ch.length
if (ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') {
countLetter++;
}else if (ch>='0'&&ch<='9') {
countNumber++;
}else if (ch==' ') {
countSpace++;
}else {
countOther++;
}
i++;
}
System.out.println("字母"+countLetter);
System.out.println("数字"+countNumber);
System.out.println("空格"+countSpace);
System.out.println("其他"+countOther);
}
}