从用户那里获取一个字符,并在 Java 中找到用户给定的字符串中该字符的出现次数

Get a character from the user and find the no of occurrences of the character in a string given by the user in Java

计算给定字符出现的次数。编写一个程序来接受来自用户的单词。从用户那里获取一个字符并找到出现的次数。

检查给定的字符和单词是否有效

如果该单词仅包含字母且没有 space 或任何特殊字符或数字,则该单词有效。

如果该字符是单独的字母,则该字符有效。

示例输入 1: 输入一个词: 编程 输入一个字符: 米

示例输出 1:

No of 'm' present in the given word is 2

示例输入 2: 输入一个词: 编程 输入字符: s

示例输出 2:

The given character 's' not present in the given word.

示例输入 3: 输入一个词: 56 示例输出 3:

Not a valid string

示例输入 4: 输入一个词: 你好 输入字符: 6

示例输出 4:

Given character is not an alphabet

我的代码:

import java.util.Scanner;

public class OccurrenceOfChar {

    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        // Fill the code
        System.out.println("Enter a word:");
        String word=sc.nextLine();
        String words=word.toLowerCase();
        String find="";
        int len=word.length();
        int i, count=0, flag=0;
        for(i=0;i<len;i++)
        {
            char c=words.charAt(i);
            if(!(c>='a' && c<='z'))
            {
                System.out.println("Not a valid string");
                break;
            }
        }
        System.out.println("Enter the character:");
        find=sc.nextLine();
        if(!(find.length()==1) && (find.charAt(0)>='a' && (find.charAt(0)<='z')))
        {
            System.out.println("Given character is not an alphabet");
        }
        for(i=0;i<len;i++)
        {
            if(words.charAt(i)==find.charAt(0))
            {
                count++;
            }
        }
        if(count==0)
            System.out.println("The given character '"+find+"' not present in the given word.");
        else
            System.out.println("No of '"+find+"' present in the given word is "+count);
    }

   }

9个测试用例中只有2个通过。 我无法指出逻辑上的错误。

测试 3:检查字符不存在且单词大写时的逻辑

测试 4:检查字符存在且单词大写时的逻辑

测试5:检查字无效时的逻辑

测试六:检查字符无效时的逻辑

测试七:检查字符有2个数字时的逻辑

测试 8:检查单词没有字母时的逻辑

测试九:检查字符为特殊字符时的逻辑

*注意:所有测试用例的权重可能不同 +----------------------------+ | 9 项测试 运行/ 2 项测试通过 | +----------------------------+

将验证字符串的逻辑移到单独的方法中,调用此方法检查给定的单词是否为有效字符串

public boolean validateString(String str) {
      str = str.toLowerCase();
      char[] charArray = str.toCharArray();
      for (int i = 0; i < charArray.length; i++) {
         char ch = charArray[i];
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
        }
      }
      return true;
   }