读书人

【java习题7】-字符的个数

发布时间: 2012-09-12 09:21:30 作者: rapoo

【java练习题7】--字符的个数

【程序7】 ??

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 ??

1.程序分析:利用while语句,条件为输入的字符不为 '\n '. ??

?

2.

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("输入字符,输入\'\\n\'表示结束");

Scanner n=new Scanner(System.in);

String str=n.nextLine();

do {

char sp[]=str.toCharArray();

int zimu=0;

int shuzi=0;

int blank=0;

int other=0;

for (int i = 0; i < sp.length; i++) {

if((sp[i]>='a'&&sp[i]<='z')||(sp[i]>='A'&&sp[i]<='Z')){

zimu++;

}else if(sp[i]>'0'&&sp[i]<'9'){

shuzi++;

}else if(sp[i]==' '){

blank++;

}else{

other++;

}

}

System.out.println("字母有:"+zimu+"个,"+"数字有:"+shuzi+"个,"+

"空格有:"+blank+"个,"+"其他字符:"+other+"个");

System.out.println("输入字符,输入\'\\n\'表示结束");

str=n.nextLine();

} while (!str.equals("\\n"));

}

读书人网 >编程

热点推荐