java - 计算出现次数
问题描述
我正在尝试编写一个代码来计算另一个字符串中 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”。
解决方案
您的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.");
}
推荐阅读
- python - 谁使用 tf.estimator.train_and_evaluate 提前停止评估损失?
- javascript - 如何遍历存储在mysql中的用户图库图片
- neo4j - WHERE 子句中存在的子查询和 OR 导致 UnknownError
- reactjs - React Hooks 如何到达 componentWillUnmount
- path - Sublime Text 3 和处理 3
- bash - 使用 bash 脚本根据数组中的值更新文件中列中的值
- html - Bootstrap 列将其他列中的元素向下推
- r - 明显的 R 错误——R 将错误的颜色与图形上的线条关联起来
- java - 如何在不使用任何循环的情况下无限期地向用户询问输入?
- bash - 从 MacOS 终端向一组文件添加文件扩展名