gpt4 book ai didi

java - 对简单的 While 循环感到困惑 - 躲在 table 下面

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

我正在阅读一本有关 Java 的书,并发现了以下源代码。

//This example demonstrates how to search multiple occurences of a search string
public class SearchString3 {
public static void main(String[] s) {
String str = "I am a student. I am preparing for OCPJP";
int fromIndex = 0;
while(str.indexOf("am", fromIndex) > -1) {
fromIndex = str.indexOf("am", fromIndex);
System.out.println("Substring \"am\" occrs at index: " + fromIndex);
fromIndex++;

}
}

}

我很困惑“fromIndex”变量是如何递增的。看起来 while 循环中的代码只运行两次,但它必须运行整个字符串长度。此代码来自 Sharma 和 Ganesh 的 Oracle 认证专业 Java SE 7 程序员考试 1Z0-804 和 1Z0-805 的第 207 页。

fromIndex 变量是如何更新的?看起来 while 循环除了两次之外不会为真。 while 循环如何对字符串的每个字符执行?有谁知道如何添加一些代码来调试这个?对不起,我的大脑今天不工作,我昨晚没睡好。

最佳答案

第一轮:

fromIndex = str.indexOf("am", fromIndex); // search from index 0, result is 2,  I (a)m a student, character (a)
System.out.println("Substring \"am\" occrs at index: " + fromIndex); // print ---> Substring "am" occrs at index: 2
fromIndex++; // increment fromIndex to 3

第二轮:

fromIndex = str.indexOf("am", fromIndex); // search from index 3, I a(m) a student, character (m)
System.out.println("Substring \"am\" occrs at index: " + fromIndex); // print ---> Substring "am" occrs at index: 18
fromIndex++; // increment fromIndex to 19, I a(m) prepa, the m character

完成。

关于java - 对简单的 While 循环感到困惑 - 躲在 table 下面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52043496/

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