java算法大全之统计出其中英文字母、空格、数字和其它字符的个数



java算法大全之统计出其中英文字母、空格、数字和其它字符的个数。算法题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。统计字符类型写了重载的两个方法,一个接受字符串作为参数,一个接受文件作为参数。

实例代码:

import java.io.BufferedReader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Basic7 {
private int number = 0;
private int bigLetter = 0;
private int smallLetter = 0;
private int space = 0;
private int others = 0;

public static void main(String[] args) {
Basic7 my1 = new Basic7();
Basic7 my2 = new Basic7();
String myString = “akhfahueueb24837 yiufa/.;.,gjakhghwuihg\\ajkahgjab9028748565″;
String fileName = “C:\\Users\\风中徜徉\\Desktop\\liujunfeng.txt”;
File myFile = new File(fileName);
my1.statistic(myString);
my2.statistic(myFile);
}
public void statistic(String astring)
{


byte mybytes[] = astring.getBytes();
for(byte b :mybytes)
{
if(b>=’0′ &&b<=’9′)
{
number++;
}
if(b>=’a’ &&b<=’z')
{
smallLetter++;
}if(b>=’A’ &&b<=’Z')
{
bigLetter++;
}
if(b==’ ‘)
{
space++;
}
else{others++;}

}
System.out.println(“数字”+number+” 小写字母 “+smallLetter+” 大写字母”+bigLetter+” 空格”+space+” 其他”+others);

}
public void statistic(File afile)
{

BufferedReader br =null ;
try {
br = new BufferedReader(new FileReader(afile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(afile.getAbsolutePath()+”文件不存在”);
//e.printStackTrace();
}
String temp;
try {
while((temp=br.readLine())!=null)
{
byte mybytes[] = temp.getBytes();
for(byte b :mybytes)
{
if(b>=0 &&b<=9)
{
number++;
}
if(b>=’a’ &&b<=’z')
{
smallLetter++;
}if(b>=’A’ &&b<=’Z')
{
bigLetter++;
}
if(b==’ ‘)
{
space++;
}
else{others++;}

}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(“数字”+number+” 小写字母 “+smallLetter+” 大写字母”+bigLetter+” 空格”+space+” 其他”+others);
}
}