Java , 以数字开头的单词

Java , words that start with a number

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

}

问题是你只调用了循环外的方法。 (当 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);

样本Input/Output:

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