我的作业是制作递归方法来计算给定字符串中给定字母的外观。这是我到目前为止的代码:使用Java中的递归方法计算字符串中的特定字符
import java.util.Scanner;
public class Exercise18_10 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.next();
System.out.print("Enter a character: ");
String letter = sc.next();
char a = letter.charAt(0);
System.out.println("The count of " + a + " is: " + count(str, a));
}
public static int count(String str, char a) {
int count = str.indexOf(a);
return count;
}
}
在count
,我用indexOf
找到所需字母第一次出现,但我不知道以后该怎么办。
你知道如果你只是一支纸和笔,你会怎么做? –
你知道'indexOf(...)'是做什么的吗? – Turing85
是的,它发现第一个出现的指定字符 –