gpt4 book ai didi

java - 计算给定字符串中某个字符的出现次数

转载 作者:行者123 更新时间:2023-12-01 05:27:01 27 4
gpt4 key购买 nike

我愣住了下面的代码,用于计算字符串中字符的出现次数:

public static void main(String[] args) {
String source = "hello low how ale you";
Scanner in = new Scanner(System.in);
String temp = in.nextLine();
char test = temp.toCharArray()[0];

int fromIndex = 0;
int occurences =0;

while(fromIndex>-1)
{
fromIndex = source.indexOf(test, fromIndex);
System.out.println("found at"+fromIndex);
//if(fromIndex!=-1) occurences++;
}
System.out.println(occurences);
}

如果“if(fromIndex!=-1)”行被注释掉,循环将无限运行!如果同一行未注释,循环将正确终止。奇怪的是,循环的终止取决于变量 fromIndex,而不是取决于在 If block 内更新的变量 occurrences 的更新。

有什么猜测为什么会发生这种情况吗?

最佳答案

fromIndex 值在后续迭代中不会更改。这就是无限循环背后的原因。那是因为 fromIndex 将给出字符的确切索引。在下一个循环中将 fromIndex 加 1,这样就可以解决问题。

while(fromIndex>-1)         
{
fromIndex = source.indexOf(test, fromIndex+1);
System.out.println("found at"+fromIndex);
if(fromIndex!=-1) occurences++;
}
}

希望这有帮助。

关于java - 计算给定字符串中某个字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9564529/

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