简体   繁体   English

查找元素在Java中出现的次数

[英]Finding the number of times an element occurs in Java

public int howMany(String element) {
    int amt = 0;
    for (int i = 0; i < log.length; i++) {
        if (element.equalsIgnoreCase(log[i]))
            amt = amt+1;
        }
    return amt;
    }
}

That's the code I have currently. 那就是我目前的代码。 It takes the element that's provided, and goes through a loop counting how many times it occurs in the form of amt. 它采用提供的元素,并循环遍历以amt形式计数的次数。 However, when I actually run one of the tests that expects a number other than 0, it fails, since for some reason, whatever number is given to it by howMany IS 0, no matter what. 但是,当我实际运行的测试中期望有一个非0的数字时,它会失败,因为由于某种原因,无论如何,HowMany IS 0赋予它的数字是多少。 Even if I change amt to 5 at the start, it's still 0 when a test like the following is run. 即使我在一开始将amt更改为5,但在运行如下所示的测试时,它仍然为0。

public void test_1_match_at_beginning() {   
    strLog.insert("string 1"); strLog.insert("string 2");
    strLog.insert("string 3"); strLog.insert("string 4");
    strLog.insert("string 5"); 

    assertEquals(1, strLog.howMany("string 1"));        
}

What is there I can do to fix this? 我可以采取什么措施解决此问题? Because as I see it, I don't know WHAT is even causing it. 因为如我所见,我什至不知道是什么原因造成的。

EDIT: Oops. 编辑:糟糕。 The test for the array version of the test was commented out. 阵列版本的测试已被注释掉。 What was actually running was the linked version, which I hadn't changed yet. 实际运行的是链接版本,但尚未更改。 Sorry for the waste of time everyone. 抱歉浪费大家的时间。

One big problem of your code is, your return is put in incorrect place. 您的代码的一个大问题是,您的退货放置在错误的位置。 You should notice that if you proper indent your code. 您应该注意,如果适当缩进代码。 Return is now put in the for loop, which mean, after it checks the first element, it returns the amt . 现在,将return放入for循环中,这意味着在检查第一个元素之后,它将返回amt Though it may not cause the problem you described (always returning 0?), this is certainly a big problem that you need to deal with. 尽管它可能不会导致您描述的问题(总是返回0?),但这肯定是您需要解决的大问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM