Java,以数字开头的单词

Java,以数字开头的单词,java,count,numbers,word,charat,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 = 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;
    }
stringword=”“;
int值=0;
而(!word.equalsIgnoreCase(“退出”)){
系统输出打印(“键入单词或退出退出:”;
word=scan.nextLine();
} 
值=数字计数(字);
System.out.print(“以数字开头的字数为“+值”);
}
公共静态整数计数(字符串str){
整数计数=0;
字符c=str.charAt(0);

如果(c>='0'&&c,则问题在于您只在循环外调用该方法。(当退出条件为
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);
样本输入/输出:


问题是,您只在循环外调用方法。(当退出条件为
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);
样本输入/输出:


你尝试过调试是否在In条件中发生了什么?<代码> Word < /代码>是代码>“退出”<代码>,你只需循环直到它开始。如何从一个数字开始?考虑删除< <代码>编号>(<代码> MeDD并替换为<代码> if(Word。匹配(\\D.*)))你是否尝试过调试,看看在No.CalpUnt中IF条件下会发生什么吗?<代码> Word < /C> >是“代码”>“退出”< /Cord>。