首页 > 解决方案 > 计算出现次数

问题描述

我正在尝试编写一个代码来计算另一个字符串中 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”。

标签: java

解决方案


您的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.");
   }

推荐阅读