【问题标题】:While loop doesn't run a indexOf searchWhile 循环不运行 indexOf 搜索
【发布时间】:2013-10-16 23:33:29
【问题描述】:

我试图找出一个字符串出现在另一个字符串中的次数。对于我的测试,我对 wordOne 使用“ea”,对 wordTwo 使用“Ilikedthebestontheeastbeachleast”。我的“外观”变量的输出返回 0,它应该存储“ea”在 wordTwo 中出现的次数。

以下是相关代码部分:

int wordTwoLength = wordTwo.length();
  System.out.println(wordTwoLength);

  while (wordTwoLength > 0)
  {
     positionCount = wordTwo.indexOf(wordOne, positionCount);
     appearances = appearances++;
     wordTwoLength = (wordTwoLength - positionCount);
  }
  System.out.println(appearances);

【问题讨论】:

  • 为什么不行?
  • 单元测试,使用IDE调试。你试过什么/
  • 我们还没有在课堂上学习单元测试IDE。我的最终打印语句只返回 0。没有错误,但它没有给出我期望的输出,即 3。
  • 修复外观++之后,它现在返回 2 而不是 3。我尝试将 positionCount 初始化为 1 而不是 0,但仍然得到相同的返回 2。

标签: java string indexof


【解决方案1】:

什么意思

 appearances = appearances++;

这将确保出现始终为零。

不应该只是外表++吗?

【讨论】:

    【解决方案2】:

    问题在于您设置外观值的位置。有区别

    appearances = appearances++;
    

    appearances = ++appearances;
    

    您将分配外观的值,然后增加“旧”外观变量。你会想要增加它然后分配它。

    或者,你可以写

    appearances++;
    

    【讨论】:

      【解决方案3】:

      这里有两个错误。

      一个是你写了appearances = appearances++; 而不仅仅是appearances++;。这样做的效果是appearances递增,然后重置为之前的值;换句话说,没有任何变化。

      第二个错误是您在第一次之后开始每次搜索,在找到匹配项的位置。所以你只是一遍又一遍地找到相同的匹配。因此,您的输出将取决于在wordTwoLength 变为负数之前您可以减去多少次positionCount

      如果需要的话,我会这样写这个方法。

      public int numberOfOccurrences(String toExamine, String toFind) {
          int currentPosition = 0;
          int occurrences = 0;
      
          for(;;) {
             int index = toExamine.indexOf(toFind, currentPosition);
             if (index == -1) {
                 return occurrences;
             }
             currentPosition = index + toFind.length();
             occurrences++;
          } 
      }
      

      【讨论】:

      • 知道为什么它会输出 2 而不是 3 的外观吗?我认为这是我的 positionCount 变量初始化为 0 的问题,所以我将其更改为 1,但仍然得到相同的输出。
      • 您每次都只是找到第一个“ea”。您将 positionCount 设置为错误的东西。用调试器试试,你会看到发生了什么。
      【解决方案4】:

      我认为这可能是您的问题。行“外观=外观++;”在您的情况下,会将外观设置为 0。这是因为 ++ 运算符会增加变量但返回原始数字。您只想输入“appearances++;”。

      即它需要外观(即 0)向其添加 1(使其值为 1)然后返回 0。所以基本上该语句等效于“外观 = 0;”。

      【讨论】:

        猜你喜欢
        • 2014-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-15
        • 2018-04-05
        • 1970-01-01
        相关资源
        最近更新 更多