gpt4 book ai didi

Java,以数字开头的单词

转载 作者:行者123 更新时间:2023-12-01 19:45:37 25 4
gpt4 key购买 nike

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

输入/输出示例:

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

关于Java,以数字开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53510460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com