问: java 如何实现利用 while 语句,条件为输入的字符不为'\n'.

2015-07-29 17:33:27 +08:00
 chenhui7373

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

关键是 java 如何实现利用while语句,条件为输入的字符不为'\n'.

2441 次点击
所在节点    Java
6 条回复
KentY
2015-07-29 17:36:08 +08:00
怀疑是写作业啊, 先把你现有的代码贴上来看看
unique
2015-07-29 17:48:40 +08:00
final String str = "asdasd as8 923 (*&)^%$";

Pattern pattern = Pattern.compile("[a-zA-Z]+");
Matcher m = pattern.matcher(str);
int yw = 0,sz = 0, kg = 0, other = 0;
while (m.find()) {
yw += m.group().length();
}
System.out.println("英文:" + yw);

pattern = Pattern.compile("[\\d]+");
m = pattern.matcher(str);
while (m.find()) {
sz += m.group().length();
}
System.out.println("数字:" + sz);

pattern = Pattern.compile("[\\s]+");
m = pattern.matcher(str);
while (m.find()) {
kg += m.group().length();
}
System.out.println("空格:" + kg);

pattern = Pattern.compile("[^a-zA-Z0-9\\s]+");
m = pattern.matcher(str);
while (m.find()) {
other += m.group().length();
}
System.out.println("其他字符:" + other);

楼主是这个意思?
incompatible
2015-07-29 17:51:41 +08:00
楼主想偏了
直接用java.util.Scanner.nextLine()就可以读一行字符了。
chenhui7373
2015-07-29 19:45:20 +08:00
@incompatible 想找和c那样getchar(),在摸索java的路上。。。多谢提醒
q397064399
2015-07-29 23:58:05 +08:00
所有的Java语言的布道者 都不推荐使用基本类型数据结构 个人建议多用java标准容器 然后去理解这些容器 比你学用基础类型要快的多 另外用面向对象的思想来解决问题 不用oo学Java 等于白学 还不如去学c
zhantss
2015-07-30 11:08:34 +08:00
int number = 0;
int space = 0;
int letter = 0;
int other = 0;
while(true) {
char c = (char) System.in.read();
//System.out.println(c);
if ('\n' == c) {
break;
}
if (c >= 48 && c <= 57)
number++;
else if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
letter++;
else if (c == 32)
space++;
else other++;
}
System.out.println(number);
System.out.println(space);
System.out.println(letter);
System.out.println(other);

这个意思?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/209320

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX