Java,以数字开头的单词

时间:2018-11-28 00:48:02

标签: java count numbers word charat

我想知道为什么计数不返回除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;
    }

}

1 个答案:

答案 0 :(得分:3)

问题在于您只能在循环外部调用该方法。 (当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