-3
编写一个程序,要求用户输入两个字符串,并打印出第二个字符串出现在第一个字符串内的次数。例如,如果第一个字符串是“香蕉”,第二是“一”,该程序将打印2字符串内部的Java字符串
下面是我到目前为止的代码
public class Assignment4 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
当我键入香蕉切成第一串,和第二个字符串是“an”,唯一出现的是数字3,它是出现3次的字符a,但不是2,因为它假设只是2“an”
使用[indexOf](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)) –