题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
这个比较简单,只要记住规律即可,代码如下:
import java.util.Scanner;
public class tongjizifugeshu {
public static void main(String[] args) {
int english = 0;
int blank = 0;
int digital = 0;
int other = 0;
char[] ch = null;
Scanner shuru = new Scanner(System.in);
System.out.println("请输入一串字符:");
String s = shuru.nextLine();
ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] >= '0' && ch[i] <= '9') {
digital ++;
}
else if ((ch[i] >= 'a' && ch[i] <= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')) {
english ++;
}
else if (ch[i] == ' ') {
blank ++;
}
else {
other ++;
}
}
System.out.println("数字个数:" + digital);
System.out.println("英文字母:" + english);
System.out.println("空格字符:" + blank);
System.out.println("其他字符:" + other);
}
}
把题目再改进一下,输入一个目录中文档的行数,字符数,数字,空格数和其他
这里需要用到java的读文件方法,用readline把文件读取,这个是一次性读取一行,并且自动忽略了结尾的换行符,也就是说,如果你不在读完一行后强制换行,那么就输出的就是一行东西了。
具体代码如下:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class duquwenjian {
public static void main(String[] args) {
try {
readtxt();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String readtxt() throws IOException {
FileReader a = new FileReader("C:/Users/Administrator/Desktop/test/test.txt");
BufferedReader br = new BufferedReader(a);
String str = "";
String r = br.readLine();
while (r != null) {
str += r + "\n";
r = br.readLine();
}
try {
char[] ch = readtxt().toCharArray();
int line = 0;
int zifu = 0;
int blank = 0;
int number = 0;
int other = 0;
for (int i = 0; i < ch.length; i ++){
if (ch[i] == '\n') {
line ++;
}
else if (ch[i] >= '0' && ch[i] <= '9') {
number ++;
}
else if ((ch[i] >= 'a' && ch[i] <= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')) {
zifu ++;
}
else if (ch[i] == ' ') {
blank ++;
}
else {
other ++;
}
}
System.out.println("行数:" + line);
System.out.println("数字:" + number);
System.out.println("字母:" + zifu);
System.out.println("空格数:" + blank);
System.out.println("其他字符:" + other);
System.out.println(readtxt());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
}