我正在尝试编写一个代码,该代码将计算另一个字符串中1个字符串的出现次数。因此,如果用户输入“ hello”,然后输入“ e”,则代码应显示“出现1次” e”。但是,我的当前代码执行了无限循环。
我尝试将for循环的条件更改为inputEntry.equals(inputCharacter)
,但也遇到了无限循环。
package charcounter;
import java.util.Scanner;
public class CharCounter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputEntry;
String inputCharacter;
System.out.println("Please enter a multi word string: ");
inputEntry = scnr.nextLine();
System.out.println("Enter another string: ");
inputCharacter = scnr.nextLine();
if (inputCharacter.length() == 1){
while (inputEntry.contains(inputCharacter)){
int occurrences = 0;
for(occurrences = 0;inputEntry.contains(inputCharacter); occurrences++ ){
System.out.println("There is " + occurrences + " of " + inputCharacter);
}
}
}
else{
System.out.println("Your string is too long.");
}
}
}
因此,如果用户输入“ hello”然后输入“ e”,则代码应显示“出现1次” e”。
答案 0 :(得分:0)
代码中的inputEntry.contains(inputCharacter)
始终返回true =>无限循环
您可以根据需要将其更改为indexOf。
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = inputEntry.indexOf(inputCharacter,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += inputCharacter.length();
}
}
您可以将代码更改为
if (inputCharacter.length() == 1){
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = inputEntry.indexOf(inputCharacter,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += inputCharacter.length();
}
}
System.out.println("There is " + count + " of " + inputCharacter);
}
else{
System.out.println("Your string is too long.");
}