【发布时间】:2018-05-07 17:10:14
【问题描述】:
我必须使用提供的循环来计算字符“b”出现在 String FourthString 中的次数,并且由于某种原因它返回了不正确的数字。我相信这与 if 条件有关,但我可能会弄错。
任何帮助将不胜感激。
字符串:
String FourthString = "棒球棒";
它应该返回 3。
代码格式:
char target ='b';
int length = fourthString.length( );
int count = 0;
int startNxtSrch = 0;
int foundAt = 0;
while( ....... ) {
foundAt = .......;
if ( ....... ) {
startNxtSrch = foundAt +1;
count += 1;
} else {
startNxtSrch = length;
}
}
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n",
count,
target );
我尝试返回的数字不正确:
int i = 0;
while( i < length ) {
foundAt = startNxtSrch;
if ( fourthString.indexOf('b', startNxtSrch) != -1 ) {
startNxtSrch = foundAt + 1;
count += 1;
i++;
} else {
startNxtSrch = length;
i++;
}
}
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n",
count,
target );
【问题讨论】:
-
谢谢。我实际上已经查看了这篇文章,但它没有帮助,因为我的问题必须适合特定的格式,我相信这个问题与循环有关,而不是字符的计数,因此是标题。
-
在我看来条件应该是
startNxtSrch < length。但我同意其他一些 cmets:这是一种非常复杂的方法。而且您可能不应该添加i变量。我相信模板中已经存在所有必要的变量。
标签: java loops if-statement while-loop conditional