问题说明如下:给定一个字符串和用户给出的字符,找出该字符(由用户给出)在字符串(也由用户给出)中重复的次数。
我有这段代码
public int repeticion (int s){
int return = 0;
int cont = 0;
Scanner in = new Scanner(System.in);
System.out.println("Write a string: ");
String chain = in.next();
System.out.println("Write the character: ");
String character = in.next();
if (chain.contains(character)) {
cont = cont + 1;
}
System.out.println("The character repeats itself "+cont+"times");
return return;
但正如您所看到的,.contains
仅计算字符一次,而不是它在字符串中出现的次数。