代码之家  ›  专栏  ›  技术社区  ›  Ken Sinelli

使用while循环、子字符串和indexOf的简单Java问题

  •  0
  • Ken Sinelli  · 技术社区  · 4 年前

    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,但我无法理解为什么会发生这种情况。我花了几个小时想弄明白。。。

    请帮忙:(

    2 回复  |  直到 4 年前
        1
  •  0
  •   Willis Blackburn    4 年前

    该计划有几个问题:

    1. passedString 对于 (":") + 1 哪根是弦 ":1" ,可能不是你想要的。

    2. 你应该评估一下 endOfSubstring categories 在循环内。

    public static void printCategories(String passedString) {
        
        int startOfSubstring = passedString.indexOf(":") + 1;
        
        while(startOfSubstring > 0) {
            int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
            // If "category:whatever" can appear at the end of the string
            // without a space, adjust endOfSubstring here.
            String categories = passedString.substring(startOfSubstring, endOfSubstring);
            // Do something with categories here, maybe print it?
            // Find next ":" starting with end of category string.
            startOfSubstring = passedString.indexOf(":", endOfSubstring) + 1; 
        }
    
    }
    
        2
  •  0
  •   ControlAltDel    4 年前

    while(startOfSubstring > 0) { // better if you do startOfSubstring != -1 IMO
        System.out.println(categories);
        // this should be startOfSubstring = passedString.indexOf(":", startOfSubstring +1);
        startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories)); 
        System.out.println(startOfSubstring);
        System.out.println(categories);
    }