以下代码不正确。当我输入字符串“ The rain in Spain”时,输出应为0,应为2。或者当我输入“ in in in”时,输出应为1,应为3。所以请帮我看看,并告诉我如何更改它以使其工作。谢谢!
import java.util.Scanner;
public class Assignment5b {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = keyboard.next();
String findStr = "in";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1){
count ++;
lastIndex+=findStr.length();
}
}
System.out.print("Pattern matches: " + count);
}}
最佳答案
将String str = keyboard.next();
替换为String str = keyboard.nextLine();
.next()方法仅扫描下一个标记。当nextLine()扫描输入的整个行,直到您按回车。
关于java - 如何使输出显示字符串中出现2个特定字母多少次?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22680851/