我的代码应该提示用户输入一个字符串和一个字符,并告诉该字符所在的位置 例如 “欢迎”和“e” 返回 “2、7”
如何修复我的代码?代码在这里。提前致谢(这不是家庭作业,但如果您不想发布解决方案,一些提示可能会很有用)。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please enter a string and a character");
Scanner input = new Scanner(System.in);
String s = input.nextLine();
char ch = input.next().charAt(0);
System.out.println(count(ch));
}
public static int count (String s, char a) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == a) {
count++;
}
}
return count;
}
}
最佳答案
一些错误:
您的代码无法编译。调用:
System.out.println(count(s, ch));
而不是
System.out.println(count(ch));
您计算出现的次数。相反,您应该保留索引。您可以使用
String
,也可以将它们添加到列表/数组中,然后将其转换为您想要的内容。public static String count(String s, char a) { String result = ""; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == a) { result += (i+1) + ", "; } } return result.substring(0, result.length() - 2); }
我使用
i+1
而不是i
,因为 Java 中索引从0
开始。我还返回了没有最后 2 个字符的字符串
result.substring(0, result.length() - 2)
,因为我在每个字符后面添加了,
。
关于Java 查找某个字符出现次数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40447322/