【问题标题】:Java , words that start with a number [duplicate]Java,以数字开头的单词[重复]
【发布时间】:2018-11-28 00:48:01
【问题描述】:

我想知道为什么计数除了 0 之外什么都不返回。我想知道是否可以在没有数组的情况下以这种方式完成。感谢您的帮助,谢谢!

    String word= "";
    int value = 0;

    while(!word.equalsIgnoreCase("Exit")){
        System.out.print("Type words or exit to quit: ");
        word = scan.nextLine();


    } 
        value = numberCount(word);
        System.out.print("The number of words that start with a number is "+value);
}
    public static int numberCount(String str){
        int count =0;
        char c = str.charAt(0);
        if(c >= '0' && c <= '9'){
            count++;
        }
        return count;
    }

}

【问题讨论】:

  • 您是否尝试过调试以查看 numberCount 中的 if 条件会发生什么?
  • word"Exit" 而你只是循环直到它是。怎么以数字开头?
  • 考虑删除您的numberCount() 方法并替换为if (word.matches("\\d.*")) count++;

标签: java count numbers word charat


【解决方案1】:

问题是你只在循环之外调用方法。 (当word 将是退出条件时,"Exit" 不以数字开头)这使得您的程序将始终打印 0。使用您的计数器变量并将方法调用移动到循环内,以便检查输入的每个单词:

while(!word.equalsIgnoreCase("Exit")){
    System.out.print("Type words or exit to quit: ");
    word = scan.nextLine();
    value += numberCount(word);
}   
System.out.print("The number of words that start with a number is "+value);

示例输入/输出:

Type words or exit to quit: 2foo
Type words or exit to quit: foo
Type words or exit to quit: 3foo
Type words or exit to quit: 10foo
Type words or exit to quit: Exit
The number of words that start with a number is 3

【讨论】:

    猜你喜欢
    • 2011-07-23
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    相关资源
    最近更新 更多