public static void main(String[] args) {
String str = "We have a large inventory of things in our warehouse falling in "
+ "the category:apperal and the slightly "
+ "more in demand category:makeup along with the category:furniture and _.";
printCategories(str);
}
public static void printCategories(String passedString) {
int startOfSubstring = passedString.indexOf(":") + 1;
int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
String categories = passedString.substring(startOfSubstring,endOfSubstring);
while(startOfSubstring > 0) {
System.out.println(categories);
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
System.out.println(startOfSubstring);
System.out.println(categories);
}
}
所以程序应该打印:
上诉
化妆
家具
一旦找不到“:”了,indexOf(startofstring的一部分)将返回-1,循环将终止。但是,在打印第一个类别之后,它会一直返回-1并在找到下一个类别之前终止。
System.out.println(startOfSubstring);
System.out.println(categories);
确认在打印第一个category之后返回-1,最后一行确认categories变量仍被定义为“apperal”。如果我把这句话注释掉:
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
它将startofstring返回为77。因此,这与该行有关,并试图更改indexOf方法中的搜索开始位置,这导致它过早地返回-1,但我无法理解为什么会发生这种情况。我花了几个小时想弄明白。。。
请帮忙:(