我在下面有这个代码,我的目标是计算字符串"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
希望你能帮助我。
答案 0 :(得分:3)
修复代码的最简单方法是将计数方法中的逻辑更改为
int a = 0;
for (char x : tiles.toCharArray()) {
if (x == letter) {
a += 1;
}
}
return a;
但有更好的方法。
您可能希望看作this old StackOverflow question,这是您正在处理的问题的更通用的解决方案。
答案 1 :(得分:1)
indexOf(String target)方法在给定字符串内从左向右搜索“目标”字符串。 indexOf()方法返回首次找到目标字符串的索引号,如果未找到目标,则返回-1。因此,如果'e'存在,它将返回true。 你没有在你的循环中的任何地方使用变量x。也许你可以试试,
Meteor.users
而不是
autopublish
答案 2 :(得分:0)
由于您正在使用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();
}