V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
chenhui7373
V2EX  ›  Java

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

  •  
  •   chenhui7373 · 2015-07-29 17:33:27 +08:00 · 2436 次点击
    这是一个创建于 3191 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    6 条回复    2015-07-30 11:08:34 +08:00
    KentY
        1
    KentY  
       2015-07-29 17:36:08 +08:00
    怀疑是写作业啊, 先把你现有的代码贴上来看看
    unique
        2
    unique  
       2015-07-29 17:48:40 +08:00   ❤️ 1
    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
        3
    incompatible  
       2015-07-29 17:51:41 +08:00
    楼主想偏了
    直接用java.util.Scanner.nextLine()就可以读一行字符了。
    chenhui7373
        4
    chenhui7373  
    OP
       2015-07-29 19:45:20 +08:00
    @incompatible 想找和c那样getchar(),在摸索java的路上。。。多谢提醒
    q397064399
        5
    q397064399  
       2015-07-29 23:58:05 +08:00 via iPad
    所有的Java语言的布道者 都不推荐使用基本类型数据结构 个人建议多用java标准容器 然后去理解这些容器 比你学用基础类型要快的多 另外用面向对象的思想来解决问题 不用oo学Java 等于白学 还不如去学c
    zhantss
        6
    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);

    这个意思?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5379 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 07:11 · PVG 15:11 · LAX 00:11 · JFK 03:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.