【问题标题】:Count using Enhanced for loop使用增强的 for 循环计数
【发布时间】:2017-05-28 00:31:21
【问题描述】:

我在下面有这段代码,我的目标是计算字符串"abcdee" 中有多少个字母“e”。

class Sample1 {
    String tiles;

    public Sample1 (String tiles) {
        this.tiles = tiles;
    }

    public int countLetter(char letter) {
        int a = 0;      
        for (char x : tiles.toCharArray()) {
            int m = 0;
            if (tiles.indexOf(letter) != -1) {
                m = 1;
            }
            a += m;
            System.out.println("Letter count is " + m); 
        }
        return a;
    }
}

public class Sample {

    public static void main(String[] args) {
        Sample1 s = new Sample1("abcdee");
        s.countLetter('e'); 

    }
}

我希望代码会给我这个结果:

Letter count is 0
Letter count is 0
Letter count is 0
Letter count is 0
Letter count is 1
Letter count is 1

然后可能将所有的 1 相加得到 2。但是当我运行它时,我得到的只是这个:

Letter count is 1
Letter count is 1
Letter count is 1
Letter count is 1
Letter count is 1
Letter count is 1

希望你能帮帮我。

【问题讨论】:

  • 你是要打印出 a 的值而不是 m 的值吗?
  • 使用流的单线:return tiles.chars().filter(c -> c == letter).count().
  • @beat 你的意思是Arrays.toStream(tiles.toCharArray()).filter(c -> c == letter).count()
  • 如果letter 存在于titles 中,tiles.indexOf(letter) 将输出有效的非负索引。在您的代码中,在循环执行期间两者都没有改变。 abcdee 确实包含 e 因此它的打印是这样的
  • @JigarJoshi 不,我的意思是CharSequence#chars(),它直接给你一个字符流。

标签: java foreach


【解决方案1】:

修复代码的最简单方法是将计数方法中的逻辑更改为

    int a = 0;      
    for (char x : tiles.toCharArray()) {
        if (x == letter) {
            a += 1;
        }
    }
    return a;

不过,还有更好的方法。

您可能希望看起来像this old Stack Overflow question,这是您正在处理的问题的更通用的解决方案。

【讨论】:

  • 谢谢雷,我应该保持简单...谢谢提醒我...你是忍者.. :)
【解决方案2】:

indexOf(String target) 方法在给定字符串中从左到右搜索“目标”字符串。 indexOf() 方法返回第一次找到目标字符串的索引号,如果没有找到目标,则返回 -1。因此,如果 'e' 存在,它将返回 true 。 首先,您没有在循环中的任何地方使用变量 x。也许您可以尝试,

if (x == letter) {
  a+ = 1
}

而不是

if (tiles.indexOf(letter) != -1) {
  m = 1;
}

【讨论】:

    【解决方案3】:

    它会重复打印1,因为您使用的是indexOf 方法,这意味着只要字母e 存在于字符串tiles 中,它就会始终打印字母数为1.要解决手头的问题,只需更改:

    if (tiles.indexOf(letter) != -1)
    

    到:

    if (x == letter)
    

    从 java-8 返回字母计数的更简单的解决方案是:

    public int countLetter(char letter) {
           return (int)tiles.chars().filter(e -> e == letter).count();
    }
    

    【讨论】:

    • 在应用基于字符的过滤器时为什么不使用chars()
    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 2014-02-23
    • 2023-03-08
    • 2020-11-22
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多